> df1 <- data.frame(group=c("red", "red", "red", "blue", "blue", "blue"), id=c("A", "B", "C", "D", "E", "F")) df1 <- data.frame(group=c("red", "red", "red", "blue", "blue", + "blue"), id=c("A", "B", "C", "D", "E", "F")) > df1 group id 1 red A 2 red B 3 red C 4 blue D 5 blue E 6 blue F > with(df1, split(id, group)) $blue [1] D E F Levels: A B C D E F
$red [1] A B C Levels: A B C D E F On Sun, Mar 25, 2012 at 4:46 PM, Ed Siefker <ebs15...@gmail.com> wrote: > I have data that looks like this: > > > df1 > group id > 1 red A > 2 red B > 3 red C > 4 blue D > 5 blue E > 6 blue F > > > I want a list of the groups containing vectors with the ids. I am > avoiding subset(), as it is > only recommended for interactive use. Here's what I have so far: > > df1 <- data.frame(group=c("red", "red", "red", "blue", "blue", > "blue"), id=c("A", "B", "C", "D", "E", "F")) > > groups <- levels(df1$group) > byid <- lapply(groups, "==", df1$group) > groupIDX <- lapply(byid, which) > > > groupIDX > [[1]] > [1] 4 5 6 > > [[2]] > [1] 1 2 3 > > > > This gives me a list of the indices for each group. I want to subset > df1 based on this list. > If I want just one group I can do this: > > > df1[groupIDX[[1]],]$id > [1] D E F > > > What sort of statement should I use if I want a result like: > [[1]] > [1] D E F > Levels: A B C D E F > > [[2]] > [1] A B C > Levels: A B C D E F > > > So far, I've used a for loop. Can I express this with apply statements? > > groupIDs <- list(1:length(groupIDX)) > groupData<- > for (i in 1:length(groupIDX)) { > groupIDs[[i]] <- df1[groupIDX[[i]],]$id > } > > ______________________________________________ > R-help@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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] ______________________________________________ R-help@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.