[R] use variable in for loop to name output files

David Winsemius dwinsemius at comcast.net
Mon Dec 10 23:02:40 CET 2012


On Dec 10, 2012, at 1:03 PM, john-usace wrote:

> Hi,
>
> This question should be simple to answer. I am a new R user.
>
> I have a data.frame called appended. I would like to break it into 7  
> smaller
> datasets based on the value of a categorical variable dp (which has  
> values
> 1:7). I would like to name the smaller datasets set1, set2,  
> set3,....,set7.
> I don't know how to refer to the variable in the for loop, when  
> naming the
> output datasets. In STATA (which I am much more familiar with) each  
> i in the
> foreach loop would be refered to as `i'. This is the code I've  
> included
> below. I've also tried set[[i]] and set[i] neither works.
>
> for (i in 1:7) {
> 	set`i' = appended[which(appended$dp==i & appended$sampled==0), ]

I am not aware of any set function, nor can one append back-ticked  
characters to unquoted characters and expect anything useful to happen.


> 	write.table(set`i', file = "output\\set`i'.csv", sep = ",",  
> row.name=F)
> 	}
>
> I'm assuming I just need to replace `' with something else but I can  
> figure
> out what that something else is.
>

In R the easy way would be to create a list that holds all of the  
split dataframes:

newlist <- split( appended, catvar)
names(newlist) <- paste0("set", 1:7)

If you goal were just to have these in your workspace, you are done.  
If you goal is to write them out to a file then you can either save it  
as one object to be later pulled back into a session with the load(.)  
command using this:

save(newlist, "newlist.Rdata")

Or you can write each individually with

lapply(names(newlist) , function(dfrm) {
                       write.table(newlist[[dfrm]],
                             file=paste0( dfrm, ".csv", sep=",",  
rowname=FALSE) }

(Untested. You should read the help pages of the various functions  
mentioned.)
-- 

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list