Skip to content
Prev 307776 / 398503 Next

Repeating a series of commands

This is pretty confusing writeup, but if you have iterations, then yes, you need a loop or a recursion.

A loop is probably easier, take a look at 

?"for"

or

?apply

for this.

there are several derivates of apply

for example, say your outputs are what the code below gives you for each file, then first make a vector with the files
 filevec<-c("f1.csv","f2.csv")

then you can easily get the "results" (a$z,b$z) as another vector by using

outputs <- sapply(filevec,function(x){
	contents<-read.csv(x);
	something<- ifelse(
		x$Z=="L",sample(1:4,length(x$Z),replace=TRUE),
		ifelse(x$Z=="M",sample(5:8,length(x$Z),replace=TRUE),
		ifelse(x$Z=="U",sample(9:10,length(x$Z),replace=TRUE),"")));
	return(something)
})

and if you want to do this several times:

m<- matrix(ncol=length(filevec),nrow=10)
myResult<- as.data.frame(m)

for(i in 1:10){
	outputs <- sapply(filevec,function(x){
	contents<-read.csv(x);
	something<- ifelse(
		contents$Z=="L",sample(1:4,length(contents$Z),replace=TRUE),
		ifelse(contents$Z=="M",sample(5:8,length(contents$Z),replace=TRUE),
		ifelse(contents$Z=="U",sample(9:10,length(contents$Z),replace=TRUE),"")));
	return(something)
	})
	someStructure[i,]<-outputs
}

If you don't know the number of iterations or outputs beforehand, i'd have a look at "while" and use lists.

Hope this helps.
On 11.10.2012, at 20:09, KoopaTrooper wrote: