2017-09-02 31 views
1

的列表替换列值我有dataframes的下面的示例清单:在dataframes

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 

我想与来自另一数据帧相应的列来替换dog列中的每个数据帧。

创建与变量“狗”

new.dog1 <- c(1,1,2,2,3) 
new.dog2 <- c(10,10,20,20,30) 
new.dog3 <- c(100,100,200,200,300) 
new.dogs <- cbind(new.dog1, new.dog2, new.dog3) 
new.dogs 

    new.dog1 new.dog2 new.dog3 
[1,]  1  10  100 
[2,]  1  10  100 
[3,]  2  20  200 
[4,]  2  20  200 
[5,]  3  30  300 

伪什么,我试图做的代码(不工作)新值的数据帧:

updated.list <- for(i in list.1) { 
    list.1[[i]][,2] <- new.dogs[,i] 
    return(list.1) 
    } 

什么输出应该是这样的:

> 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 

在我的for循环,我认为这个问题是new.dogs[,i]位的代码?理想情况下,我宁愿用lapply或大于如果可能的话一个for循环一个tidyverse解决方案......

回答

1

如果你想使用tidyverse,你可以继续new.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)) 
2

而且随着基础R:

updated.list <- mapply(function(old, new, which) { 
    old[,which] <- new 
    old 
}, list.1, data.frame(new.dogs), "dog", SIMPLIFY = FALSE) 
+0

谢谢你,你的答案的伟大工程也一样,我接受了内特,因为他首先回答一个nd我要求提供一种全新的或基本的解决方案(如果我能接受这两个答案,这将是非常好的)。 – flee