[R] adding columns to dataframes contained in a list

Patrick Connolly p_connolly at slingshot.co.nz
Wed May 4 12:12:36 CEST 2011


On Wed, 04-May-2011 at 10:25AM +0300, E Hofstadler wrote:

|> hi there,
|> 
|> I have a list of 5 identical dataframes:
|> 
|> mydf <- data.frame(x=c(1:5), y=c(21:25))
|> mylist <- rep(list(mydf),5)
|> 
|> and a factor variable with 5 levels:
|> 
|> foo <- c(letters[1:5])
|> foo <- as.factor(foo)
|> 
|> 
|> Question:
|> I'd like to add a new variable to each dataframe in the list, each
|> containing only one level of the factor variable. So mylist[[1]]
|> should have a new variable z containing only "a", in mylist[[2]]  the
|> new variable z should contain only "b", etc.
|> 
|> (How) can this be done without looping?

This will work:

zz <- do.call("rbind", mylist)
zz$z <- rep(foo, each = 5)
split(zz, zz$z)

You might want to rename of the list elements if those are
inconvenient.


HTH

|> 
|> All help is greatly appreciated.
|> 
|> Best,
|> Esther
|> 
|> ______________________________________________
|> 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.

-- 
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.   
   ___    Patrick Connolly   
 {~._.~}                   Great minds discuss ideas    
 _( Y )_  	         Average minds discuss events 
(:_~*~_:)                  Small minds discuss people  
 (_)-(_)  	                      ..... Eleanor Roosevelt
	  
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.



More information about the R-help mailing list