[R] Still confused with lapply

Ken Knoblauch ken.knoblauch at inserm.fr
Fri Nov 19 15:54:04 CET 2010


PtitBleu <ptit_bleu <at> yahoo.fr> writes:

> 
> 
> Hello,
> 
> I would like to replace a for loop with lapply in order to speed up the
> treatment of my data (I've read lapply can help to do it).
> 
> At the end of the message, you will find a simple example (function is more
> complex and data frames is more than 1 million of rows) of what I would like
> to do, that is applying the same calculation to all the rows of the data
> frame (knowing that I cannot change the structure of the function).
> 
> I hope you understand my french explainations ...
> Thanks in advance for your help,
> Have a nice week-end,
> Ptit Bleu.
> 
> df1<-data.frame(c(1,2,3,4), c(9,6,5,8), c(5,4,8,6))
> names(df1)<-c("C1", "C2", "C3")
> 
> fcttest<-function(a1,a2,a3) {
>   v<-a1*a2
>   w<-a2+a3
> return(c(v,w))
> }
> 
> # The following for loop works
> result<-data.frame()
> for (i in 1:length(df1[,1])) {
> result<-rbind(result,fcttest(df1[i,1],df1[i,2],df1[i,3]))



why bother with lapply when you can just do this

with(df1, cbind(df1[[1]] * df1[[2]], df1[[2]] + df1[[3]]))

HTH

Ken

-- 
Ken Knoblauch
Inserm U846
Stem-cell and Brain Research Institute
Department of Integrative Neurosciences
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.sbri.fr/members/kenneth-knoblauch.html



More information about the R-help mailing list