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

arun smartpink111 at yahoo.com
Mon Apr 7 12:59:04 CEST 2014


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