2014-01-30 38 views
0

我有一個命令在R(index1,index2,index3 ...等)中每10個循環生成一個變量。我擁有的命令是功能性的,但我正在考慮編寫此命令的更智能的方法。這是我的命令是這樣的:在R中的每n個循環中生成一個新變量

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 ....我相信有一些簡單的方法來做到這一點,但我不能想到它。

謝謝。

+1

也許結果? – hd1

+0

他們必須是'index1'等嗎?爲什麼不把它們附加到矢量?你打算如何使用它們? – doctorlove

+0

我試圖做一些像索引[計數器] < - 數據[計數器],但我無法讓命令工作。 – Error404

回答

2

你需要的是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. 
+1

除了在變量名稱中使用數字是一個失敗 - 創建一個列表並分配給列表的元素。 – Spacedman

+0

@Spacedman,肯定壞習慣很難死。 – 2014-01-30 14:08:42

+0

謝謝,這是我想要做的:) – Error404