[R] replace a for loop

Petr PIKAL petr.pikal at precheza.cz
Wed Feb 10 17:03:35 CET 2010


Hi

how many objects do you have in a list? Loop is ineffective if you use 
several nested loops and/or there is some unnecessary mimic of simple 
function.

e.g. you can use this

set.seed(666)
x <- runif(10)
vysled <- 0
for(i in 1:length(x)) {
if(vysled > x[i]) vysled <- vysled else vysled <- x[i]
}
vysled

but I would prefer max(x)

If you do not perceive performance issues there is usually no need to 
elaborate *apply.

Regards
Petr



r-help-bounces at r-project.org napsal dne 10.02.2010 11:59:21:

> After reading the R news, I've tried this code and it works:
>  > rapply(list(names(test),test), write.csv, file="filename.csv", 
> append=T, row.names=F)
> 
> However, the output is structured like this:
> names(test)[[1]]
> names(test)[[2]]
> etc...
> test[[1]]
> test[[2]]
> etc...
> 
> I would like to alternate names(test) and test in the output. The 
> desired output would be structured like this:
> names(test)[[1]]
> test[[1]]
> names(test)[[2]]
> test[[2]]
> etc...
> 
> Can someone guide me for that step? Better solutions for the whole thing 

> are of course welcomed!
> 
> Thanks a lot
> Ivan
> 
> Le 2/10/2010 10:50, Ivan Calandra a écrit :
> > Hi everybody!
> >
> > I'm still quite new in R and I don't really understand this whole 
> > "vectorization" thing.
> > For now, I use a for loop (and it works fine), but I think it would be 

> > useful to replace it.
> >
> > I want to export the result of a test statistic, which is stored as a 
> > list, into a csv file. I therefore have to export each element of the 
> > list separately.
> > Here is the code:
> > ----
> > str(test)
> > List of 3
> >  $ output : num [1:15, 1:6] 1 2 3 4 5 6 7 8 9 10 ...
> >   ..- attr(*, "dimnames")=List of 2
> >   .. ..$ : NULL
> >   .. ..$ : chr [1:6] "con.num" "psihat" "p.value" "p.crit" ...
> >  $ con    : num [1:6, 1:15] 1 -1 0 0 0 0 1 0 -1 0 ...
> >  $ num.sig: int 0
> >
> > for (i in 1:3){
> >  write.csv(test[[i]], file="filename.csv", append=T, quote=F, 
> > row.names=T)
> > }
> > ----
> >
> > As I said, I don't completely understand, but I think one of these 
> > "apply" function might do what I need.
> >
> > Thanks in advance
> > Ivan
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide 
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list