2016-04-27 68 views
0

我有一個數據框,其中對於每個Filename值,都有一組Compound值。某些化合物具有IS.Name的值,該值是文件名的複合值之一。R:需要爲數據框中的每一行執行多個匹配

,Batch,Index,Filename,Sample.Name,Compound,Chrom.1.Name,Chrom.1.RT,IS.Name,IS.RT 
1,Batch1,1,Batch1-001,Sample001,Compound1,1,0.639883333,IS-1,0 
2,Batch1,1,Batch1-001,Sample001,IS-1,IS1,0.61,NONE,0 

對於每一組,在我的數據幀相同的文件名的值的行,我想匹配與相應的化合物的值IS.Name值,以及從匹配的行把Chrom.1.RT值進入IS.RT細胞。例如,在上述我想從行2取Chrom.1.RT值對化合物表= IS-1,放入IS.RT在行1是這樣的:

,Batch,Index,Filename,Sample.Name,Compound,Chrom.1.Name,Chrom.1.RT,IS.Name,IS.RT 
1,Batch1,1,Batch1-001,Sample001,Compound1,1,0.639883333,IS-1,0.61 
2,Batch1,1,Batch1-001,Sample001,IS-1,IS1,0.61,NONE,0 

如果可能我需要在R做到這一點。在此先感謝您的幫助!

編輯:這裏是一個更大,更詳細的例子:

Filename Compound Chrom.1.RT IS.Name IS.RT 
1 Sample-001 IS-1 1.32495 NONE NA 
2 Sample-001 Compound-1 1.344033333 IS-1 NA 
3 Sample-001 IS-2 0.127416667 NONE NA 
4 Sample-001 Compound-2 0 IS-2 NA 
5 Sample-002 IS-1 1.32495 NONE NA 
6 Sample-002 Compound-1 1.344033333 IS-1 NA 
7 Sample-002 IS-2 0.127416667 NONE NA 
8 Sample-002 Compound-2 0 IS-2 NA 

這是色譜數據。對於每個樣品,正在分析四種化合物,每種化合物都有一個保留時間值(Chrom.1.RT)。其中兩種化合物是其他兩種化合物使用的參考。例如,化合物-1使用IS-1,而IS-1沒有參考(IS)。在每個示例中,我試圖將IS名稱與複合行匹配,以便抓取CHrom.1.RT並將其放入IS.RT字段中。因此對於化合物-1,我想找到與IS.Name字段(IS-1)具有相同名稱的化合物的Chrom.1.RT值,並將其放入化合物-1的IS.RT字段中。我正在處理的表格列出了所有化合物,並且與引用的值不匹配,我需要爲下一步計算Chrom.1.RT和IS.RT之間的差異複合。這有幫助嗎?

編輯 - 這是我發現,似乎工作的代碼:

sampleList<- unique(df1$Filename) 
for (i in sampleList){ 
    SampleRows<-which(df1$Filename == sampleList[i]) 
    RefRows <- subset(df1, Filename== sampleList[i]) 
    df1$IS.RT[SampleRows]<- RefRows$Chrom.1.RT[ match(df1$IS.Name[SampleRows], RefRows$Compound)] 
    } 

我絕對歡迎任何建議,讓雖然這更有效率。

+0

謝謝akrun的格式化幫助! – krazeechemist78

+0

嘗試'df1 $ IS.RT < - 與(df1,Chrom.1.RT [match(IS.Name,Compound)])'並用0替換爲'NA' – akrun

+0

對於IS.Name中的值與一個化合物相匹配,它將0放入IS.RT中,而不是正確地獲取Chrom.1.RT值。我有類似的結果使用df1 $ IS.RT < - df1 $ Chrom.1.RT [match(df1 $ IS.Name,df1 $ Compound)]。 – krazeechemist78

回答

0

首先,我在未來建議你提供你的例子如dput(DF1),因爲它使人們更方便把它讀成R,而不是您所提供

的空間分隔表的輸出據說,我已經設法用MS Excel的「幫助」將它與R進行了討論。

df1=structure(list(Filename = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L), .Label = c("Sample-001", "Sample-002"), class = "factor"), 
Compound = structure(c(3L, 1L, 4L, 2L, 3L, 1L, 4L, 2L), .Label = c("Compound-1", 
"Compound-2", "IS-1", "IS-2"), class = "factor"), Chrom.1.RT = c(1.32495, 
1.344033333, 0.127416667, 0, 1.32495, 1.344033333, 0.127416667, 
0), IS.Name = structure(c(3L, 1L, 3L, 2L, 3L, 1L, 3L, 2L), .Label = c("IS-1", 
"IS-2", "NONE"), class = "factor"), IS.RT = c(NA, NA, NA, 
NA, NA, NA, NA, NA)), .Names = c("Filename", "Compound", 
"Chrom.1.RT", "IS.Name", "IS.RT"), class = "data.frame", row.names = c(NA, 
-8L)) 

下面的代碼是嚴重笨重,但它的工作。

library("dplyr") 
df1=tbl_df(df1) 
left_join(df1,left_join(df1%>%select(-Compound),df1%>%group_by(Compound)%>%summarise(unique(Chrom.1.RT)),c("IS.Name"="Compound")))%>%select(-IS.RT)%>%rename(IS.RT=`unique(Chrom.1.RT)`) 

除非我弄錯了,這是你需要的嗎?

+0

在更好的例子中增加了一些更多的細節,並提出了一個代碼解決方案。感謝您的建議! – krazeechemist78

相關問題