如何修改 R 中一系列列表的元素?
How to modify elements of a range of lists in R?
示例如下:
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)
现在我要做的是将 index
指定的所有 R
列表中的 r[1]
更改为 2
。如果我们有一个大小为 1 的索引,那么解决方案将是 R[[index]]$r[1]=2
。但是当我们有一系列索引时呢?实现这一目标的最有效方法是什么?
感谢@rawr 关于使用 replace()
的建议
library(purrr)
index<-c(2,3,6)
modify_at(R, index,~list(r=replace(.$r, 1, 2)))
针对下面的评论,您可以将第一个元素替换为第一个元素加 2,如下所示:
R <- modify_at(R, index,~list(r=replace(.$r, 1, .$r[1]+2)))
示例如下:
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)
现在我要做的是将 index
指定的所有 R
列表中的 r[1]
更改为 2
。如果我们有一个大小为 1 的索引,那么解决方案将是 R[[index]]$r[1]=2
。但是当我们有一系列索引时呢?实现这一目标的最有效方法是什么?
感谢@rawr 关于使用 replace()
library(purrr)
index<-c(2,3,6)
modify_at(R, index,~list(r=replace(.$r, 1, 2)))
针对下面的评论,您可以将第一个元素替换为第一个元素加 2,如下所示:
R <- modify_at(R, index,~list(r=replace(.$r, 1, .$r[1]+2)))