[R] looping variable names

Greg Snow Greg.Snow at imail.org
Thu Feb 3 18:23:28 CET 2011


It depends on what you are assigning.  A simple example of assigning the values 1 through 100:

mylist <- lapply(1:100, I)
names(mylist) <- paste('var',1:100, sep='')

Or if you have 100 files named dat1.txt, dat2.txt, ..., dat100.txt and you want to read them in:

mylist <- lapply( paste('dat', 1:100, '.txt', sep=''), function(fname) read.table(fname, header=TRUE) )
names(mylist) <- paste('dat',1:100, sep='')

if I want to use dataset 1 I can do it with:

> mylist$dat1
Or
> mylist[['dat1']]
Or
> milyst[[1]]

Then if I want to do the same regression on each of the 100 datasets (assuming the names are the same) I can do that with a simple:

out1 <- lapply( mylist, function(dat) lm( y ~ x, data=dat ) )

then maybe I want all the slopes in a single vector:

slopes <- sapply( out1, function(fit) coef(fit)[1] )

hope this helps,


-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of hypermonkey22
> Sent: Wednesday, February 02, 2011 4:57 PM
> To: r-help at r-project.org
> Subject: Re: [R] looping variable names
> 
> 
> Thanks for the reply!
> 
> This sounds great. Is there a nice way to store these 100 variable
> names in
> a list without typing them all out?
> --
> View this message in context: http://r.789695.n4.nabble.com/looping-
> variable-names-tp3255711p3256356.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