我想简化我目前用向量替换数据框的列值的方法。我在下面使用基础R的解决方案中提供了可重复的答案。简化版本仅包含一个数据框,并且包含多个数据框,由于解决方案不好,我不得不使用for循环。
如何简化方法?
# Simplified version
Df <- data.frame(a = c(1,2,3),
b = c(4,5,6),
c = c(7,8,9))
l <- list(c(11,22,33),
c(44,55,66))
letters <- c("a","b")
Df[letters] <- l
# Multiple data frames
Df1 <- list(data.frame(a = c(1,2,3),
b = c(4,5,6),
c = c(7,8,9)),
data.frame(a = c(101,102,103),
b = c(104,105,106),
c = c(107,108,109)))
l <- list( list(c(11,22,33), c(44,55,66)),
list(c(111,222,333), c(444,555,666)) )
letters <- c("a","b")
for(i in 1:length(Df1)){
Df1[[i]][letters] <- l[[i]]
}
答案 0 :(得分:1)
这里是map2
library(purrr)
library(dplyr)
map2(Df1, l, ~ {.x[letters] <- .y; .x})
或者使用inset
中的magrittr
library(magrittr)
map2(Df1, l, ~ inset(.x, letters, value = .y))
或成链形
map2(Df1, l, ~ .x %>%
select(-one_of(letters)) %>%
bind_cols(.y %>%
set_names(letters)) %>%
select(names(.x)))
或者在base R
Map(function(x, y) {x[letters] <- y;x}, Df1, l)