如何在R中修改一系列列表的元素?
以下是一个例子:如何在R中修改一系列列表的元素?,r,list,lapply,purrr,R,List,Lapply,Purrr,以下是一个例子: R<-vector("list",10) #a list of 10 elements r<-rep(0,5) # each list includes this vector #we add the vector to all lists for(i in 1:10) { R[[i]]$r=r } index<-c(2,3,6) R感谢@rawr关于使用replace() 库(purrr) 您是否不想再次使用循环代码对于(索
R<-vector("list",10) #a list of 10 elements
r<-rep(0,5) # each list includes this vector
#we add the vector to all lists
for(i in 1:10)
{
R[[i]]$r=r
}
index<-c(2,3,6)
R感谢@rawr关于使用replace()
库(purrr)
您是否不想再次使用循环代码<代码>对于(索引中的i)R[[i]]$R[1],我正在寻找比循环更有效的东西。另外,如果您能告诉我如何用更高效的方法替换第一个循环,那就太好了。@Mild这将与您的循环做同样的事情:map(1:10,~list(r=r))
@DaveArmstrong谢谢!这看起来不错!但是让我们让这个问题更有趣一点。如果我们想像这样更新每个r[1]
,r[1]=r[1]+2
,该怎么办?@Milad我相应地编辑了答案。我还修改了第一个答案,以保留所有更改列表的初始格式。
library(purrr)
index<-c(2,3,6)
modify_at(R, index,~list(r=replace(.$r, 1, 2)))
R <- modify_at(R, index,~list(r=replace(.$r, 1, .$r[1]+2)))