R 替换数据帧列表中的列值
我有以下数据帧示例列表:R 替换数据帧列表中的列值,r,list,for-loop,lapply,tidyverse,R,List,For Loop,Lapply,Tidyverse,我有以下数据帧示例列表: cat <- rnorm(5) dog <- rnorm(5) mouse <- rnorm(5) df1 <- cbind(cat,dog,mouse) df2 <- cbind(cat,dog,mouse) df3 <- cbind(cat,dog,mouse) list.1 <- list(df1 = df1,df2 = df2,df3 = df3) list.1 $df1 cat
cat <- rnorm(5)
dog <- rnorm(5)
mouse <- rnorm(5)
df1 <- cbind(cat,dog,mouse)
df2 <- cbind(cat,dog,mouse)
df3 <- cbind(cat,dog,mouse)
list.1 <- list(df1 = df1,df2 = df2,df3 = df3)
list.1
$df1
cat dog mouse
[1,] -0.6991598 -0.8630006 -0.7564806
[2,] 0.7645475 1.3571995 0.8939621
[3,] 1.0608070 -0.8455111 0.5198387
[4,] -0.2008916 -0.7971714 0.8477894
[5,] -0.6988800 1.0717351 -1.3684944
$df2
cat dog mouse
[1,] -0.6991598 -0.8630006 -0.7564806
[2,] 0.7645475 1.3571995 0.8939621
[3,] 1.0608070 -0.8455111 0.5198387
[4,] -0.2008916 -0.7971714 0.8477894
[5,] -0.6988800 1.0717351 -1.3684944
$df3
cat dog mouse
[1,] -0.6991598 -0.8630006 -0.7564806
[2,] 0.7645475 1.3571995 0.8939621
[3,] 1.0608070 -0.8455111 0.5198387
[4,] -0.2008916 -0.7971714 0.8477894
[5,] -0.6988800 1.0717351 -1.3684944
我尝试执行的操作的伪代码(不起作用):
在我的for循环中,我认为问题在于
new.dogs[,I]
bit代码?理想情况下,我宁愿使用lappy
或tidyverse
解决方案,也不愿使用for循环(如果可能的话…如果你想使用tidyverse
,你可以保留新的.dogs
一个列表,并清理遗留下来的矩阵混乱cbind()
,然后使用map2()
要成对地遍历两个列表,如下所示:
library(tidyverse)
# use new.dogs as a list instead
new.dogs <- list(new.dog1, new.dog2, new.dog3)
# cbind() creates matrixes from vectors, not tidy tibbles/dataframes
list.1 <- map(list.1, as.tibble)
# iterate and replace pairwise (list.1[[i]] <- .; new.dogs[[i]] <- .y)
map2(list.1, new.dogs, ~ mutate(., dog = .y))
库(tidyverse)
#使用new.dogs作为列表
new.dogs和带R基的:
updated.list <- mapply(function(old, new, which) {
old[,which] <- new
old
}, list.1, data.frame(new.dogs), "dog", SIMPLIFY = FALSE)
updated.list谢谢,你的答案也很好,我接受了Nate,因为他先回答了,我要的是tidyverse或base解决方案(如果我能同时接受这两个答案就太好了)。
> updated.list
$df1
cat dog mouse
[1,] -0.6991598 1 -0.7564806
[2,] 0.7645475 1 0.8939621
[3,] 1.0608070 2 0.5198387
[4,] -0.2008916 2 0.8477894
[5,] -0.6988800 3 -1.3684944
$df2
cat dog mouse
[1,] -0.6991598 10 -0.7564806
[2,] 0.7645475 10 0.8939621
[3,] 1.0608070 20 0.5198387
[4,] -0.2008916 20 0.8477894
[5,] -0.6988800 30 -1.3684944
$df3
cat dog mouse
[1,] -0.6991598 100 -0.7564806
[2,] 0.7645475 100 0.8939621
[3,] 1.0608070 200 0.5198387
[4,] -0.2008916 200 0.8477894
[5,] -0.6988800 300 -1.3684944
library(tidyverse)
# use new.dogs as a list instead
new.dogs <- list(new.dog1, new.dog2, new.dog3)
# cbind() creates matrixes from vectors, not tidy tibbles/dataframes
list.1 <- map(list.1, as.tibble)
# iterate and replace pairwise (list.1[[i]] <- .; new.dogs[[i]] <- .y)
map2(list.1, new.dogs, ~ mutate(., dog = .y))
updated.list <- mapply(function(old, new, which) {
old[,which] <- new
old
}, list.1, data.frame(new.dogs), "dog", SIMPLIFY = FALSE)