gpt4 book ai didi

替换数据框列表中的列值

转载 作者:行者123 更新时间:2023-12-02 09:17:03 26 4
gpt4 key购买 nike

我有以下数据框示例列表:

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] 代码位上?理想情况下,如果可能的话,我宁愿使用 lapplytidyverse 解决方案,也不愿使用 for 循环...

最佳答案

并以 R 为基数:

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

关于替换数据框列表中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com