为什么不能在value.var
中将多个变量传递给dcast
?从?dcast
:
它没有明确指出只能将一个变量作为值传递。但是,如果我尝试这样做,则会收到错误消息:
> 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
因此,施加此限制是否有充分的理由?并且有可能解决此问题(也许使用
reshape
等)吗? 最佳答案
这个问题与your other question from earlier today非常相关。
@beginneR在评论中写道:“只要现有数据已经是长格式,我认为在类型转换之前就不需要将其熔化。”在针对其他问题的答复中,我举了一个示例,说明何时需要melt
,或者更确切地说,如何确定数据是否足够长。
这里的问题是另一个示例,该示例说明由于不满足my answer中的第3点,何时需要进一步的melt
编码。
要获得所需的行为,请尝试以下操作:
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
,然后使用reshape
或dcast
从“long”变为“wide”。这两个都是必需的,因为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
关于r - 为什么在 `value.var`中不能有几个 `dcast`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25143428/