[R] for (i in ...) { df[[i]]<- .....}

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Aug 27 15:35:49 CEST 2004


"Luis Rideau Cruz" <Luisr at frs.fo> writes:

> R-help,
> 
> In the following loop :
> 
> for(i in 1:8)
> {
> cc[[i]]<-tapply(test[,i+6],list(puntar=test$puntar),sum)/tapply(test[,5],list(puntar=test$puntar),sum)
> 
> cbind.data.frame(cc[[1]],cc[[2]],cc[[3]],cc[[4]],
> cc[[5]],c[[6]],cc[[7]],cc[[8]])
> 
> }
> 
> Is there anyway I can 'cbind.data.frame' the objects cc[[ i ]] without
> actually writing every single element??
> In this case there are 8 but what if it is a large number??

Whatever did as.data.frame(cc) do to you to deserve getting overlooked
that badly? (and I suspect that there's a much neater solution
along the lines of

dd <- lapply(test[5:14],tapply,test$puntar,sum)
dd <- as.data.frame(lapply(dd,as.vector))
dd <- dd[-1]/dd[[1]]

)

As for the generic question, have a look at do.call().

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list