Why can't there be multiple `value.var` in` dcast`?

Why can't multiple variables be passed in value.varto dcast? From ?dcast:

value.var is the name of the column in which values ​​are stored, see gt_value for default strategies to figure this out.

It does not explicitly state that only one variable can be passed as a value. If, however, I try this, then I get an error message:

> 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 any good reason to impose this restriction? And is it possible to get around this (possibly using reshape, etc.)?

+4
source share
3 answers

.

@beginneR , " , ". , , , melt, , , .

, melt ing, 3 .

, :

C93L <- melt(Cars93, measure.vars = c("Price", "Weight"))
dcast(C93L, AirBags ~ DriveTrain + variable, mean, value.var = "value")
#              AirBags 4WD_Price 4WD_Weight Front_Price Front_Weight
# 1 Driver & Passenger       NaN        NaN    26.17273     3393.636
# 2        Driver only     21.38       3623    18.69286     2996.250
# 3               None     13.88       2987    12.98571     2703.036
#   Rear_Price Rear_Weight
# 1      33.20      3515.0
# 2      28.23      3463.5
# 3      14.90      3610.0

aggregate mean s, reshape dcast "" "". , reshape :

temp <- aggregate(cbind(Price, Weight) ~ AirBags + DriveTrain, 
                  Cars93, mean)
#              AirBags DriveTrain    Price   Weight
# 1        Driver only        4WD 21.38000 3623.000
# 2               None        4WD 13.88000 2987.000
# 3 Driver & Passenger      Front 26.17273 3393.636
# 4        Driver only      Front 18.69286 2996.250
# 5               None      Front 12.98571 2703.036
# 6 Driver & Passenger       Rear 33.20000 3515.000
# 7        Driver only       Rear 28.23000 3463.500
# 8               None       Rear 14.90000 3610.000

reshape(temp, direction = "wide", 
        idvar = "AirBags", timevar = "DriveTrain")
#              AirBags Price.4WD Weight.4WD Price.Front Weight.Front
# 1        Driver only     21.38       3623    18.69286     2996.250
# 2               None     13.88       2987    12.98571     2703.036
# 3 Driver & Passenger        NA         NA    26.17273     3393.636
#   Price.Rear Weight.Rear
# 1      28.23      3463.5
# 2      14.90      3610.0
# 3      33.20      3515.0
+7

, : dcast .var, "" data.table dcast :

# multiple value.var
data.table::dcast(Cars93, AirBags ~ DriveTrain, mean, value.var=c("Price", "Weight"))

.

+1

Try forcing data.frame into the data table using setDT or as.data.table.

dcast(setDT(C93L), AirBags ~ DriveTrain , mean, value.var=c("Price","Weight"))
0
source

All Articles