2
$\begingroup$

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.

Thanks in advance!

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

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)
$\endgroup$
  • $\begingroup$ Perfect, thank you! I didn't think to use plyr. $\endgroup$ – Lyra Feb 16 '12 at 5:05
3
$\begingroup$

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"))
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.