Sign up ×

this question might be very simple, but I do not find a good way to solve it: I have a dataset with many subgroups which need to be analysed all-together and on their own. Therefore, I want to use subsets for the groups and use them for the later analysis. As well, the defintion of the subsets as the analysis should be partly done with loops in order to save space and to ensure that the same analysis has been done with all subgroups.

Here is an example of my code using an example dataframe from the boot package:

for (i in length(qlist)) {
    paste("aids.sub.",qlist[i],sep="") <- subset(aids, quarter==qlist[i])

The variable which contains the subgroups in my dataset is stored as a string, therefore I added the qlist part which would be not required otherwise.

share|improve this question

1 Answer 1

up vote 5 down vote accepted

Make a list of the subsets with lapply:

lapply(qlist, function(x) subset(aids, quarter==x))

Equivalently, avoiding the subset():

lapply(qlist, function(x) aids[aids$quarter==x,])

It is likely the case that using a list will make the subsequent code easier to write and understand. You can subset the list to get a single data frame (just as you can use one of the subsets, as created below). But you can also iterate over it (using for or lapply) without having to construct variable names.

To do the job as you are asking, use assign:

for (i in qlist) {
   assign(paste("aids.sub.",i,sep=""), subset(aids, quarter==i))

Note the removal of the length() function, and that this is iterating directly over qlist.

share|improve this answer
Is there a way, I can store those lists as dataframes with standardized names such as aids.sub1 to aids.sub4? I have more than 300,000 obs. which cannot even be all printed on screen. –  user1870829 Dec 9 '12 at 21:02
You can, but you probably should not. I'll edit the answer to show how. –  Matthew Lundberg Dec 9 '12 at 21:10
Great, thank you for the quick help! –  user1870829 Dec 9 '12 at 21:17
@Lonelyisland you can name the lists. You can access them by object$name and it won't clutter your workspace with "useless" variables. –  Roman Luštrik Dec 9 '12 at 22:05

Your Answer

