我有 2 个数据框
structure(list(code = c("ATT", "TTT", "ACC", "GGG"), line = c("G1",
"G2", "G3", "G3"), gspot = c("sd", "sd", "ff", "af"), plot = c(1,
1, 2, 2)), class = "data.frame", row.names = c(NA, -4L))
structure(list(code = c("ATT", "TTT"), name = c("a", "f")), class = "data.frame", row.names = c(NA,
-2L))
我想使用 df1 数据帧作为键值结构 key(code)-value(line) 用 df1$line 替换 df2$code 以产生类似的东西
structure(list(code = c("G1", "G2"), name = c("a", "f")), class = "data.frame", row.names = c(NA,
-2L))
但我想避免加入和合并,因为我不想保留 df1 的所有列
答案 0 :(得分:1)
我认为您可以使用以下解决方案:
library(dplyr)
df2 %>%
mutate(code = df1$line[match(df2$code, df1$code)])
code name
1 G1 a
2 G2 f
答案 1 :(得分:1)
我们可以在 ['A', 'B']
['A', 'B', 'C']
data.table
-输出
library(data.table)
setDT(df2)[df1, code := line, on = .(code)]