将元素添加到R中for循环的列表中 [英] Adding elements to a list in for loop in R

查看:193
本文介绍了将元素添加到R中for循环的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在for循环中添加元素到列表中。 (1:N中的i)我如何设置字段名称?

  L < 
{
#Create object Ps ...
string< -paste(element,i,sep =)
L $ get(string)< -Ps



$ b $ p
$ b

我希望列表中的每个元素具有依赖于字段名称的i(例如,第二个元素应该有element2)



如何做到这一点?我认为我的错误是使用 get

解决方案

就像你正在寻找像下面这样的结构:

  N < -  3 
x < - list )
for(i in 1:N){
Ps < - i ##其中i是你的Ps是
x [[paste0(element,i)]] - Ps
}
x
#$ element1
#[1] 1

#$ element2
#[1] 2

#$ element3
#[1] 3

虽然,如果事先知道 N ,那么分配 x 是更好的做法,并且更有效率,然后填充它而不是添加

  N < -  3 
x < - vector(list,N)
for(i in 1:N){
Ps < - i ##其中i是你的Ps是
x [[i]] < - Ps
}
setNames(x,paste0(element,1:N))
#$ element1
#[1] 1

#$ element2
# [1] 2

#$ element3
#[1 ] 3


I'm trying to add elements to a list in a for loop. How can I set the field name?

L<-list() 
    for(i in 1:N)
    {
        #Create object Ps...
        string<-paste("element",i,sep="")
        L$get(string)<-Ps
    }

I want every element of the list to have the field name dependent from i (for example, the second element should have "element2")

How to do this? I think that my error is the usage of get

解决方案

It seems like you're looking for a construct like the following:

N <- 3
x <- list()
for(i in 1:N) {
    Ps <- i  ## where i is whatever your Ps is
    x[[paste0("element", i)]] <- Ps
}
x
# $element1
# [1] 1
#
# $element2
# [1] 2
#
# $element3
# [1] 3

Although, if you know N beforehand, then it is better practice and more efficient to allocate x and then fill it rather than adding to the existing list.

N <- 3
x <- vector("list", N)
for(i in 1:N) {
    Ps <- i  ## where i is whatever your Ps is
    x[[i]] <- Ps
}
setNames(x, paste0("element", 1:N))
# $element1
# [1] 1
#
# $element2
# [1] 2
#
# $element3
# [1] 3

这篇关于将元素添加到R中for循环的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆