0

I have a piece of code which is a For Loop that carries out a function for a number of 1:n arguments. Now I would like to run this for loop 1000 times. Can I just use another for loop?

par1<-function(x,y,z)
for (i in 1:n) {
do stuff
}

How do I manage to get this piece of code repeated so that the function (x,y,z) with the following for loop is reiterated 1000 times ?

Stedy
  • 7,359
  • 14
  • 57
  • 77
Tim Heinert
  • 179
  • 3
  • 6
  • 11
  • If you want your displayed `for` loop to be a part of the function, you will need another set of braces. If you can provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of what you want to do, we can probably provide a more helpful response. – gung - Reinstate Monica Nov 25 '13 at 22:18

2 Answers2

1

You can do this.

par1<-function(x,y,z){
  for(i in 1:n){
    do stuff
  }
}

for(j in 1:1000){
  par1(something)
}
flodel
  • 87,577
  • 21
  • 185
  • 223
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
  • Hey...par1 is a variable in my case and I don't know what you mean by (something) (it is not another function with inbuild paramters). J doesn't turn up in something (so it does not matter that the runnign variable occurs there? – Tim Heinert Nov 27 '13 at 09:13
  • `par1` *cannot* be a variable; you have defined it as a function that takes 3 variables (`x`, `y`, & `z`), & does something w/ them. With respect, you may need much more fundamental advice than can be provided via SO. – gung - Reinstate Monica Nov 27 '13 at 13:59
1

It is not clear what you are trying to do. I sometimes uses sapply to loop over a function. So for example, if x, y and z are vectors of length 1000:

par1<-function(x,y,z) {
  for (i in 1:n) {
    do stuff
  }
}

sapply(1:1000, function(X) par1(x[X],y[X],z[X]))
Adrian
  • 684
  • 3
  • 20