【问题标题】:Generating a new variable every n loops in R在 R 中每 n 个循环生成一个新变量
【发布时间】:2014-01-30 13:56:43
【问题描述】:

我有一个命令,它在 R 中每 10 个循环生成一个变量(索引 1、索引 2、索引 3 ......等等)。我拥有的命令是有效的,但我正在考虑一种更聪明的方式来编写这个命令。这是我的命令的样子:

for (counter in 1:10){

for (i in 1:100){
if (counter == 1){

index1 <- data1 ## some really long command here, I just changed it to this simple command to illustrate the idea

}

if (counter == 2){

index2 <- data2    
}



.
.
.
# until I reach index10
} indexing closure
} ## counter closure

有没有办法写这个而不必写条件 if 命令?我想生成 index1, index2.... 我确信有一些简单的方法可以做到这一点,但我就是想不出。

谢谢。

【问题讨论】:

  • 也许使用向量?
  • 他们必须是index1 等吗?为什么不将它们附加到向量中?你打算如何使用它们?
  • 我试图做类似 index[counter]

标签: r variables for-loop counter naming-conventions


【解决方案1】:

您需要的是modulo 运算符%%。在内循环内部。例如:100%%10 返回 0 101%%10 返回 1 92%%10 返回 2 - 换句话说,如果它是 10 的倍数,那么你得到 0。还有 assign 函数。

注意:您不再需要示例中使用的外循环。 因此,要在每 10 次迭代中创建一个变量,请执行以下操作

for(i in 1:100){
#check if i is multiple of 10
   if(i%%10==0){
     myVar<-log(i)
    assign(paste("index",i/10,sep=""), myVar)
   }

}


ls() #shows that index1, index2, ...index10 objects have been created.
index1 #returns 2.302585

更新: 或者,您可以将结果存储在向量中

  index<-vector(length=10)
        for(i in 1:100){
        #check if i is multiple of 10
           if(i%%10==0){
             index[i/10]<-log(i)
           }

        }
index #returns a vector with 10 elements, each a result at end of an iteration that is a multiple of 10.

【讨论】:

  • 除了在变量名中使用数字是失败的 - 创建一个列表并分配给列表的元素。
  • 谢谢,这就是我想做的:)
猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多