[R] Loop over several variables

MacQueen, Don macqueen1 at llnl.gov
Thu Nov 1 15:27:15 CET 2012


Many ways. Here is one:

### supposing you have y1, y2, and y3 in your data frame

for (i in 1:3) {

  yi <- paste('y',i,sep='')

  ti <- aggregate(dataframename[[yi]],
           by=data.frame(dataframename$aggregationvar),
           sum,na.rm=TRUE)

  assign( paste('ti',i,sep='') , ti, '.GlobalEnv')
}

Or if you happen to think using assign() is bad form you can store each ti
in a list().

-Don


-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 11/1/12 4:32 AM, "bchr" <bochristoph at web.de> wrote:

>Hey everybody,
>
>I am looking for a way to loop commands over several variables in a
>dataframe. Basically I want to do something like this:
>
>ti1<-aggregate(dataframename$y1,
>               by=data.frame(dataframename$aggregationvar),
>               sum,na.rm=TRUE)
>
>This works fine as it is but i want to do it for several variables thereby
>generating several tix. I tried with a for-loop but the problem was that I
>could neither find a way combine my indexnumber i (1 ... x) with the y or
>ti
>(as for example in Stata I could do by writing y`i')  nor did it work
>using
>a vector of string variables  ("y1", ... "yx") and looping over that
>(while
>using yx also as a name for the target dataframe instead of tix - i
>would'nt
>mind that).
>
>Preferably I would be looking for a solution that can do without any of
>the
>apply functions (yes, I know they are more R-like, but frankly, I don't
>get
>the logic behind them, so for the time being I would prefer another way)
>
>Tanks very much for your help
>
>Bernhard
>
>
>
>--
>View this message in context:
>http://r.789695.n4.nabble.com/Loop-over-several-variables-tp4648112.html
>Sent from the R help mailing list archive at Nabble.com.
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list