R:在保留行名的同时按行名值和列值合并两个数据帧

R: Merging Two Dataframes by Rowname Values & Column Values whilst Preserving Rownames

我正在尝试合并两个数据帧。一个数据框包含行名,这些行名在另一个数据框的列中显示为值。我想根据这些相互值将第二个数据框中的一列 (Top.Viral.TaxID.Name) 附加到第一个数据框中。

第一个数据框如下所示:

         ERR1780367  ERR1780369  ERR2013703    xxx...    


374840      73          0            0                      
417290      56          57           20                      
1923444     57          20           102                     
349409      40          0            0                      
265522      353         401          22                       
322019      175         231          35                       

第二个数据框如下所示:

       Top.Viral.TaxID       Top.Viral.TaxID.Name


1        374840              Enterobacteria phage phiX174 sensu lato
2        417290              Saccharopolyspora erythraea prophage pSE211
3        1923444             Shahe picorna-like virus 14
4        417290              Saccharopolyspora erythraea prophage pSE211
5        981323              Gordonia phage GTE2
6        349409              Pandoravirus dulcis

但是,我还想保留第一个数据帧的行名,所以结果看起来像这样:

         ERR1780367  ERR1780369  ERR2013703    xxx...    Top.Viral.TaxID.Name


374840      73          0            0                   Enterobacteria phage phiX174 sensu lato
417290      56          57           20                  Saccharopolyspora erythraea prophage pSE211            
1923444     57          20           102                 Shahe picorna-like virus 14     
349409      40          0            0                   Pandoravirus dulcis   
265522      353         401          22                  Hyposoter fugitivus ichnovirus     
322019      175         231          35                  Acanthocystis turfacea Chlorella virus 1    

提前致谢。

使用 sapply 循环遍历数据帧 1 (df1) 的行名并在数据帧 2 (df2) 中搜索 id,返回同一行中的描述。 像这样

df1$Top.Viral.TaxID.Name <- sapply(rownames(df1), (function(id){
  df2$Top.Viral.TaxID.Name[df2$Top.Viral.TaxID == id]  
}))

我强烈建议不要依赖行名。令人尴尬的是,它们经常被删除,dplyr/tidyr 中的函数总是删除它们。

始终使行名成为数据的一部分,即使用 "tidy" 数据集,如下例

data(iris)
# We mix the data a bit, to check if rownames are conserved
iris = iris[sample.int(nrow(iris), 20),]
head(iris)

description = 
  data.frame(Species = unique(iris$Species))
description$fullname = paste("The wonderful", description$Species)
description

# .... the above are your data
iris = cbind(row = rownames(iris), iris)

# Now it is easy
merge(iris, description, by="Species")

请在 SO 中提问时使用可重现的数据以获得快速答案。将您提供的数据重新格式化为可以测试的形式需要大量工作。