[R] var[i]

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Thu May 1 19:38:13 CEST 2003


"juli g. pausas" <juli at ceam.es> writes:

> Dear all,
> How could I use variables in a loop that their names are in a vector?
> For example:
> 
> aaa <- 1:10
> bbb <- aaa*2
> ccc <- aaa+bbb
> 
> varn <- c("aaa", "bbb", "ccc")
> m <- rep(NA, 3)
> 
> for (i in 1:length(varn)) m[i] <- mean(varn[i])  # wrong

....mean(get(varn[i])).

However, the preferred method might be

sapply(list(aaa,bbb,ccc),var)

or

sapply(data.frame(aaa,bbb,ccc),var)

(which of course only works when the vectors have the same length, and
reminds me that one of the bricks in my road to Hell is to write an
nlist() which supplies element names like data.frame does...)

-- 
   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