[R] question about a small "for" loop

Wolfgang Huber huber at ebi.ac.uk
Mon Jul 14 23:33:38 CEST 2008


Christopher W. Ryan wrote:
> R 2.5.1 on WinXP
> 
> I'm trying to create new variables in a dataframe called jaw, as powers
> of jaw$age up to the sixth power, and name them
> 
> jaw$age.(--the digit corresponding to the power--)
> 
> Obviously none of these work (silly for me to try, I suppose):
> 
> for (i in 2:6) {
>   jaw$age.'i' <- jaw$age^i
>   }
> 
> for (i in 2:6) {
>   jaw$age.i <- jaw$age^i
>   }
> 
> for (i in 2:6) {
>   jaw$age."i" <- jaw$age^i
>   }
> 
> What is the proper syntax to create and name these variables all at once?
> 
> Thanks.
> 
> --Chris


for (i in 2:6)
    jaw[[paste("age", i, sep="^")]] = jaw$age^i


or

  m = outer(jaw$age, 2:6, "^")
  colnames(m) = paste("age", 2:6, sep="^")
  jaw = cbind(jaw, m)


Best wishes
  Wolfgang


-- 
----------------------------------------------------
Wolfgang Huber, EMBL-EBI, http://www.ebi.ac.uk/huber



More information about the R-help mailing list