[R] Still confused with lapply

PtitBleu ptit_bleu at yahoo.fr
Fri Nov 19 15:41:08 CET 2010


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]))
}

# But the command 
lapply(df1, fcttest)
# gives (in french, sorry)
# Erreur dans FUN(X[[1L]], ...) : l'élément 2 est vide ;
# la partie de la liste d'arguments de '*' en cours d'évaluation était :
#  (a1, a2)



-- 
View this message in context: http://r.789695.n4.nabble.com/Still-confused-with-lapply-tp3050414p3050414.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list