我有一个数据帧df
col1 col2 col3 col4 col5
row1 0.0 0.0 0.0 0.0 0.0
row2 0.0 0.4 0.4 0.0 0.0
row3 0.5 1.2 0.4 0.3 0.8
row4 3.3 1.4 1.4 1.0 6.3
row5 0.0 0.2 0.0 0.0 0.0
row6 0.8 0.0 0.0 0.0 0.2和数据帧mapping
rowname mapped_name
row1 a
row2 a
row3 a
row5 b
row6 c我想要得到
col1 col2 col3 col4 col5 mapped_name
row1 0.0 0.0 0.0 0.0 0.0 a
row2 0.0 0.4 0.4 0.0 0.0 a
row3 0.5 1.2 0.4 0.3 0.8 a
row4 3.3 1.4 1.4 1.0 6.3 NA
row5 0.0 0.2 0.0 0.0 0.0 b
row6 0.8 0.0 0.0 0.0 0.2 c因为当我做df$mapped_name <- df[mapping$rowname == rownames(df),]$mapped_name时,它们的长度是不同的
character(0)
Warning message:
In mapping$rowname == rownames(df) :
longer object length is not a multiple of shorter object length发布于 2015-09-16 22:47:43
我们可以使用‘match’数据集的'rowname‘列映射'df’的行名,使用该数字索引来获得相应的'mapped_name‘
df$mapped_name <- mapping$mapped_name[match(row.names(df), mapping$rowname)]
df
# col1 col2 col3 col4 col5 mapped_name
#row1 0.0 0.0 0.0 0.0 0.0 a
#row2 0.0 0.4 0.4 0.0 0.0 a
#row3 0.5 1.2 0.4 0.3 0.8 a
#row4 3.3 1.4 1.4 1.0 6.3 <NA>
#row5 0.0 0.2 0.0 0.0 0.0 b
#row6 0.8 0.0 0.0 0.0 0.2 chttps://stackoverflow.com/questions/32611858
复制相似问题