How to collapse groups in data defined by a group variable in R?

I have some multilevel data with a group variable (groups 1-100). Some of my other variables are within-group means, hence they have the same value repeated for every individual within group i. I'd like to reshape the data so that each group has only one line (instead of one for every individual within the group) so I can better use the within-group mean variables. For now, I don't care what happens with the individual-level variables.

I'm guessing the reshape package must be the way to go, but I haven't had any success fiddling around with it.

Edit: Here's an example of what my data look like:

groupmean = c(1.4, 1.4, 1.4, 1.4, 6.2, 6.2, 6.2, 6.2)
group = c(1, 1, 1, 1, 2, 2, 2, 2)
mydata = data.frame(group, groupmean)


The repetition is because I have additional variables representing individual-level data (that I don't care about for now). I would like to reshape the above into a dataframe with only two lines, one for each group.

• A sample of your data would help. (Or at least a similar example.) – Wayne Feb 16 '12 at 2:54
• I'll leave it here, but please ask further questions strictly about programming in R (i.e. without any statistical/ML part) on StackOverflow. – user88 Feb 16 '12 at 9:43

Does this do what you want?

groupmean <- c(1.4, 1.4, 1.4, 1.4, 6.2, 6.2, 6.2, 6.2)
group <- c(1, 1, 1, 1, 2, 2, 2, 2)
mydata <- data.frame(group, groupmean)
require(plyr)
ddply(mydata, .(groupmean), colMeans)

• Perfect, thank you! I didn't think to use plyr. – Lyra Feb 16 '12 at 5:05

No reshape needed - just

unique(mydata)


It's complicated a little if there are individual-level variables, but you just have to subset to the group variables:

mydata$id <- seq_along(mydata$group)

unique(mydata[ , c("group", "groupmean")])


Or, in plyr:

library(plyr)
count(mydata, vars = c("group", "groupmean"))