基于数据框列表,替换数据框列的值

3

dfs列表:

catbehave <- c("Good", "Cute", "Evil")
catnum <- c(1, 2, 3)
dogbehave <- c("Goodboi", "Cute")
dognum <- c(4, 2)
mousebehave <- c("Evil", "Good", "Cute")
mousenum <- c(3, 1, 2)

cat <- as.data.frame(cbind(catbehave, catnum))
dog <- as.data.frame(cbind(dogbehave, dognum))
mouse <- as.data.frame(cbind(mousebehave, mousenum))


list.1 <- list(cat = cat,dog = dog,mouse = mouse)

df1:

cat <- c("Good", "Evil", "Evil", "Cute")
dog <- c("Goodboi", "Goodboi", "Cute", "Goodboi")
mouse<- c("Evil", "Good", "Cute", "Evil")
df1 = data.frame(cat, dog, mouse)

我希望评估一系列数据框以更改 df1 中的值。需要在 list.1 中使用数据框的名称作为 df1 的列名。

输出:

df1

cat  dog  mouse
1    4    3
3    4    1
3    2    2
2    4    3
3个回答

2

假设list.1和df1有相同的顺序,一个基本的R选项如下:

df1[] <- mapply(
  function(x, y) x[y],
  lapply(list.1, function(x) setNames(x[[2]], x[[1]])),
  df1
)
df1

#   cat dog mouse
# 1   1   4     3
# 2   3   4     1
# 3   3   2     2
# 4   2   4     3

1
您可以使用match来进行更新连接
for(i in names(df1)) {
   df1[,i] <- list.1[[i]][match(df1[,i], list.1[[i]][,1]), 2]
}
df1
#  cat dog mouse
#1   1   4     3
#2   3   4     1
#3   3   2     2
#4   2   4     3

1
使用 tidyverse,我们可以这样做:
library(dplyr)
library(tibble)
library(purrr)
map2_dfc(df1, list.1, ~ deframe(.y)[.x])
# A tibble: 4 x 3
#  cat   dog   mouse
#  <chr> <chr> <chr>
#1 1     4     3    
#2 3     4     1    
#3 3     2     2    
#4 2     4     3    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接