2017-09-02 35 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