Why can't one have multiple variables passed to value.var
in dcast
? From ?dcast
:
value.var name of column which stores values, see guess_value for default strategies to figure this out.
It doesn't explicitly indicate that only one single variable can be passed on as value. If however I try that, then I get an error:
> library("reshape2")
> library("MASS")
>
> dcast(Cars93, AirBags ~ DriveTrain, mean, value.var=c("Price", "Weight"))
Error in .subset2(x, i, exact = exact) : subscript out of bounds
In addition: Warning message:
In if (!(value.var %in% names(data))) { :
the condition has length > 1 and only the first element will be used
So is there a good reason for imposing this limitation? And is it possible to work around this (perhaps using reshape
, etc.)?
This question is very much related to your other question from earlier today.
@beginneR wrote in the comments that "As long as the existing data is already in long-format, I don't see any general need to melt it before casting." In my answer posted at your other question, I gave an example of when
melt
would be required, or rather, how to decide whether your data are long enough.This question here is another example of when further
melt
ing would be required since point 3 in my answer is not satisfied.To get the behavior you want, try the following:
An alternative is to use
aggregate
to calculate themean
s, and then usereshape
ordcast
to go from "long" to "wide". Both are required sincereshape
does not perform any aggregation:I had the same issue and I found this answer: Error using dcast with multiple value.var that suggests to "force" data.table dcast function as follows:
I was able to cast multiple variables without error.
Try coercing your data.frame into a data.table using setDT or as.data.table.