我有一个销售报告表(DF1),我需要用相关的组代码替换少数产品代码
Model SOLD
A 5
B 4
C 4
D 3
F 11
我有另一张表(DF2),我有Model#和相关的组码
Model Group
A 1
B 1
C 2
D 2
如果DF2中存在模型,我想用DF1替换DF1中的模型#。
想要的最终结果:
Model SOLD
1 5
1 4
2 4
2 3
F 11
谢谢!
答案 0 :(得分:1)
您可以使用qdapTools的lookup
系列执行此操作,特别是二进制运算符%lc+%
(data.table
包的包装器)。 l
代表lookup
,c
代表character
,而+
仅替换查找表中找到的元素:
library(qdap)
df1$Model <- df1$Model %lc+% df2
这里更明确:
df1 <- structure(list(Model = structure(1:5, .Label = c("A", "B", "C",
"D", "F"), class = "factor"), SOLD = c(5L, 4L, 4L, 3L, 11L)), .Names = c("Model",
"SOLD"), class = "data.frame", row.names = c(NA, -5L))
df2 <- structure(list(Model = structure(1:4, .Label = c("A", "B", "C",
"D"), class = "factor"), Group = c(1L, 1L, 2L, 2L)), .Names = c("Model",
"Group"), class = "data.frame", row.names = c(NA, -4L))
library(qdap)
df1$Model <- df1$Model %lc+% df2
df1
## Model SOLD
## 1 1 5
## 2 1 4
## 3 2 4
## 4 2 3
## 5 F 11