# Generating a new variable every n loops in R

I have a command that generates a variable every 10 loops in R (index1, index2, index3... and so on). The command I have is functional, but I am thinking of a smarter way to write this command. Here's what my command looks like:

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

Is there a way to write this without having to write the conditional if commands? I would like to generate index1, index2.... I am sure there is some easy way to do this but I just cannot think of it.

Thanks.

## Answers

What you need is the modulo operator %%. inside the inner loop. Ex: 100%%10 returns 0 101%%10 returns 1 92%%10 returns 2 - in other words if it is multiple of 10 then you get 0. And the assign function.

Note: You no longer need the outer loop used in your example. So to create a variable at every 10 iteration do something like this

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

**update:**
Alternatively, you can store results in a vector

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.

### Need Your Help

### How can I save document files to the SQLite Database in iOS to view them later in the program?

I'm having a problem with the code I'm writing.### android- Replacing fragment in ViewPager from NavigationBar

android android-fragments android-viewpager android-cardview fragmentmanager

I'm developing an Android application that allow to view the results of hockey matches.