我有两个数据帧 DF1
structure(list(d.x = structure(c(1L, 2L, 3L, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), .Label = c("Sample1",
"Sample2", "Sample3"), class = "factor"), d.Name = structure(c(1L,
2L, 3L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA), .Label = c("A", "B", "C"), class = "factor")), .Names = c("d.x",
"d.Name"), row.names = c(NA, -37L), class = "data.frame")
DF2
structure(list(d.ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("Sample1",
"Sample2", "Sample3"), class = "factor")), .Names = "d.ID", row.names =c(NA,
-37L), class = "data.frame")
我想用df1文件的相应名称替换df2中的所有名称 举个例子 Sample1将命名为A
答案 0 :(得分:1)
您可以按如下方式使用match()
:
df2$d.Id.New <- df1$d.Name[match(df2$d.ID, df1$d.x)]
这会在df2
中创建一个新列,其中包含来自df1
的匹配值:
> head(df2)
d.ID d.Id.New
1 Sample1 A
2 Sample1 A
3 Sample1 A
4 Sample1 A
5 Sample1 A
6 Sample1 A