多次替换/查找
我有下面的数据:
data_1 = data.frame(var1 = c("A", "B", "C"), var2 = c("A1", "A2", "A3"))
data_1$var1 = as.factor(data_1$var1)
data_1$var2 = as.factor(data_1$var2)
var1 var2
1 A A1
2 B A2
3 C A3
然后我有这个查找表:
lookup = data.frame(var_1_value = c("A", "B", "C"), var_1_code = c(1,2,3), var_2_value = c("A1", "A2", "A3"), var_2_code = c(4,5,6))
var_1_value var_1_code var_2_value var_2_code
1 A 1 A1 4
2 B 2 A2 5
3 C 3 A3 6
我想用查找表中的“代码”替换“data_1”中的值。我尝试使用这个问题作为灵感(替换数据框中的值基于查找表):
lookup1 <- setNames(as.character(lookup$var_1_code), lookup$var_1_value)
res <- data.frame(lapply(data_1, function(i) lookup1[i]))
rownames(res) <- NULL
但这并没有给出预期的输出:
> res
var1 var2
1 1 1
2 2 2
3 3 3
我认为可能会发生这种情况,因为我在前面的代码中从未提到过“var2”,但这也不起作用:
lookup1 <- setNames(as.character(lookup$var_1_code), lookup$var_1_value, as.character(lookup$var_2_code), lookup$var_2_value)
res <- data.frame(lapply(data_1, function(i) lookup1[i]))
rownames(res) <- NULL
Error in setNames(as.character(lookup$var_1_code), lookup$var_1_value, :
unused arguments (as.character(lookup$var_2_code), lookup$var_2_value)
- 有人可以告诉我吗如何执行同时查找/替换多列? (例如,如果有 5 列、15 列、25 列等)
预期输出应如下所示:
> res
var1 var2
1 1 4
2 2 5
3 3 6
谢谢!
I have the data below:
data_1 = data.frame(var1 = c("A", "B", "C"), var2 = c("A1", "A2", "A3"))
data_1$var1 = as.factor(data_1$var1)
data_1$var2 = as.factor(data_1$var2)
var1 var2
1 A A1
2 B A2
3 C A3
I then have this Lookup Table:
lookup = data.frame(var_1_value = c("A", "B", "C"), var_1_code = c(1,2,3), var_2_value = c("A1", "A2", "A3"), var_2_code = c(4,5,6))
var_1_value var_1_code var_2_value var_2_code
1 A 1 A1 4
2 B 2 A2 5
3 C 3 A3 6
I want to replace the values in "data_1" with the "codes" from the Lookup Table. I tried to use this question as inspiration (Replace values in a dataframe based on lookup table):
lookup1 <- setNames(as.character(lookup$var_1_code), lookup$var_1_value)
res <- data.frame(lapply(data_1, function(i) lookup1[i]))
rownames(res) <- NULL
But this is not giving the intended output:
> res
var1 var2
1 1 1
2 2 2
3 3 3
I thought that maybe this is happening because I never mentioned "var2" in the previous code, but this also did not work:
lookup1 <- setNames(as.character(lookup$var_1_code), lookup$var_1_value, as.character(lookup$var_2_code), lookup$var_2_value)
res <- data.frame(lapply(data_1, function(i) lookup1[i]))
rownames(res) <- NULL
Error in setNames(as.character(lookup$var_1_code), lookup$var_1_value, :
unused arguments (as.character(lookup$var_2_code), lookup$var_2_value)
- Can someone please show me how to perform Lookup/Replace on multiple columns at the same time? (e.g. if there 5 columns, 15 columns, 25 columns, etc.)
The intended output should look like this:
> res
var1 var2
1 1 4
2 2 5
3 3 6
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
sapply
:生成的
res
看起来像You could use
sapply
:The resulting
res
looks like