首页 > 解决方案 > 如何修改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)

现在我想要做的是r[1]2所有Rindex. 如果我们有一个大小为 1 的索引,那么解决方案将是R[[index]]$r[1]=2. 但是当我们有一系列索引时呢?实现这一目标的最有效方法是什么?

标签: rlistlapplypurrr

解决方案


感谢@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)))

推荐阅读