[英]Replace column values in a list of 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
列替換為另一個數據框中的相應列。
用變量“ 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
或tidyverse
解決方案,也不願使用for循環...
與基數R:
updated.list <- mapply(function(old, new, which) {
old[,which] <- new
old
}, list.1, data.frame(new.dogs), "dog", SIMPLIFY = FALSE)
如果要使用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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.