[R] How to use an elements' name when creating a data frame via a for loop

arun smartpink111 at yahoo.com
Tue Apr 8 02:16:44 CEST 2014





Hi,

It is not clear what you really want.  Now, you mentions ?merge() etc.  If you don't want to use ?assign(),

lst <- list(as.data.frame(matrix(1:40,ncol=5)), as.data.frame(matrix(1:20,ncol=4)), as.data.frame(matrix(1:25,ncol=5)),as.data.frame(matrix(21:30,ncol=2)))

 stations <- c("BETB011", "BETM204", "BETN029","BETN043")
 names(lst) <- paste(stations, "PM",sep="_") 
head(lst$BETB011_PM,2)
# V1 V2 V3 V4 V5
# 1  1  9 17 25 33
# 2  2 10 18 26 34 

#or
attach(lst) #not recommended.  


head(BETB011_PM,2)
# V1 V2 V3 V4 V5 
#1  1  9 17 25 33 
#2  2 10 18 26 34 


A.K.


Hello, 
thank you for your answer. I think its already a little too advanced for me. 
I would appreciate if you would just give me a hint to the construction of the several data frames (so maybe without the assign function). 
i can merge the other data frames via the merge function, so thats not an issue for me at the moment. 
But in order to merge the data it would be handy to create the data frames upfront. 
Therefore, a for loop would be nice that simply creates data frames for every station in the station data frame and names them accordingly. 
I assume its sth like  stations <- c("BETB011", "BETM204", "BETN029","BETN043") 
for (i in 1:length(stations) 
{[i] <- data.frame(stations[i])}  Would be nice then to have 4 data.frames named BETB011, BETM204, BETN29, BETN043 or even better 
BETB011_PM, BETM204_PM, ... 
But unfortunately this does not work.





On Monday, April 7, 2014 6:59 AM, arun <smartpink111 at yahoo.com> wrote:
Hi,

May be this helps:
stations <- LETTERS[1:4]
set.seed(42)
PM2.5 <- data.frame(DateTime=seq(as.POSIXct("2010-01-10 01:00:00"),length.out=10,by= "1 day"), station= sample(LETTERS[1:4],10,replace=TRUE))
for(i in 1:length(stations))
assign(paste(stations[i],"PM",sep="_"),subset(PM2.5,station==stations[i])) 

A_PM 

#             DateTime station
#8 2010-01-17 01:00:00 A

D_PM
#             DateTime station
#1 2010-01-10 01:00:00 D 

#2 2010-01-11 01:00:00       D
#4 2010-01-13 01:00:00       D 


A.K.

Hey, I got a question that bugs me for a longer time now.  I want to create several data.frames via a for loop that is applied to the elements of a vector.
And I want to use the names of the elements in the name of the created data.frames. Is that possible?
Im confused with the coding there ... Should look something like this:   for (i in 1:length(stations)) {stations[i]_PM <- data.frame(PM2.5$DateTime,PM2.5$stations[i])} The result should be several dataframes (length of stations) with the name StationID_PM.
Should I use the paste function?? Thank you very much. Hopefuly, I explained myself well enough. Dolby




More information about the R-help mailing list