[R] avoiding for loops

Ed Siefker ebs15242 at gmail.com
Sun Mar 25 22:46:07 CEST 2012


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
	}



More information about the R-help mailing list