I am working with a dataset that comes with lme4, and am trying to learn how to apply reshape2 to convert it from long to wide [full code at the end of the post].
library(lme4)
data("VerbAgg") # load the dataset
The dataset has 9 variables; 'Anger', 'Gender', and 'id' don't vary with 'item', while 'resp', 'btype', 'situ', 'mode', and 'r2' do.
I have successfully been able to convert the dataset from long to wide format using reshape():
wide <- reshape(VerbAgg, timevar=c("item"),
idvar=c("id", 'Gender', 'Anger'), dir="wide")
Which yields 316 observations on 123 variables, and appears to be correctly transformed. However, I have had no success using reshape/reshape2 to reproduce the wide dataframe.
wide2 <- recast(VerbAgg, id + Gender + Anger ~ item + variable)
Using Gender, item, resp, id, btype, situ, mode, r2 as id variables
Error: Casting formula contains variables not found in molten data: Anger
I may not be 100% clear on how recast defines id variables, but I am very confused why it does not see "Anger". Similarly,
wide3 <- recast(VerbAgg, id + Gender + Anger ~ item + variable,
id.var = c("id", "Gender", "Anger"))
Error: Casting formula contains variables not found in molten data: item
Can anyone see what I am doing wrong? I would love to obtain a better understanding of melt/cast!
Full code:
## load the lme4 package
library(lme4)
data("VerbAgg")
head(VerbAgg)
names(VerbAgg)
# Using base reshape()
wide <- reshape(VerbAgg, timevar=c("item"),
idvar=c("id", 'Gender', 'Anger'), dir="wide")
# Using recast
library(reshape2)
wide2 <- recast(VerbAgg, id + Gender + Anger ~ item + variable)
wide3 <- recast(VerbAgg, id + Gender + Anger ~ item + variable,
id.var = c("id", "Gender", "Anger"))
# Using melt/cast
m <- melt(VerbAgg, id=c("id", "Gender", "Anger"))
wide <- o cast(m,id+Gender+Anger~...)
Aggregation requires fun.aggregate: length used as default
# Yields a list object with a length of 8?
m <- melt(VerbAgg, id=c("id", "Gender", "Anger"), measure.vars = c(4,6,7,8,9))
wide <- dcast(m, id ~ variable)
# Yields a data frame object with 6 variables.
melt
ing and thencast
ing - then you'll be able to more easily see what's going wrong. – hadley