我有两个数据帧,如下所示。我希望将数据帧1中的文本(单元格)替换为匹配时从数据帧2中获取的相应值。我试着在下面给出一个简单的例子。我对R的经验有限,但不能马上想到一个简单的解决方案。任何帮助/建议将不胜感激。
input_1 = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"),
col2 = c("A", "B", "C", "D"),
col3 = c("B", "E", "F", "D"))
input_2 = data.frame(colx = c("A", "B", "C", "D", "E", "F"),
coly = c(1, 2, 3, 4, 5, 6))
output = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"),
col2 = c(1, 2, 3, 4),
col3 = c(2, 5, 6, 4))
这是一个整齐的解决方案:
library(tidyverse)
mutate_at(input_1, -1, ~deframe(input_2)[as.character(.)])
# col1 col2 col3
# 1 ex1 1 2
# 2 ex2 2 5
# 3 ex3 3 6
# 4 ex4 4 4
deframe
从数据框架构建一个命名向量,在这种情况下更方便。
as.character
是必要的,因为你有因子列
使用tidyverse的示例。我的解决方案涉及两次合并到input_2,但匹配不同的列。最后一个管道清理数据框并重命名列。
library(tidyverse)
input_1 = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"),
col2 = c("A", "B", "C", "D"),
col3 = c("B", "E", "F", "D"))
input_2 = data.frame(colx = c("A", "B", "C", "D", "E", "F"),
coly = c(1, 2, 3, 4, 5, 6))
output = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"),
col2 = c(1, 2, 3, 4),
col3 = c(2, 5, 6, 4))
input_1 %>% inner_join(input_2, by = c("col2" = "colx")) %>%
inner_join(input_2, by = c("col3" = "colx")) %>%
select(col1, coly.x, coly.y) %>%
magrittr::set_colnames(c("col1", "col2", "col3"))
使用基数R的一种方法是循环遍历我们想要使用lapply
更改值的列,match
使用input_2$colx
的值并获得相应的coly
值。
input_1[-1] <- lapply(input_1[-1], function(x) input_2$coly[match(x, input_2$colx)])
input_1
# col1 col2 col3
#1 ex1 1 2
#2 ex2 2 5
#3 ex3 3 6
#4 ex4 4 4
实际上,你可以不使用lapply
离开,你可以直接unlist
值和match
input_1[-1] <- input_2$coly[match(unlist(input_1[-1]), input_2$colx)]