gpt4 book ai didi

r - 为什么不能在 `value.var` 中有几个 `dcast` ?

转载 作者:行者123 更新时间:2023-12-04 11:11:34 25 4
gpt4 key购买 nike

为什么不能将多个变量传递给 value.vardcast ?来自 ?dcast :

value.var name of column which stores values, see guess_value for default strategies to figure this out.



它没有明确表示只能传递一个变量作为值。但是,如果我尝试这样做,则会出现错误:
> 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将需要,或者更确切地说,如何确定您的数据是否足够长。

这里的这个问题是另一个例子,当进一步meltmy answer 中的第 3 点起就需要 ing不满意。

要获得您想要的行为,请尝试以下操作:

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,然后使用 reshapedcast从“长”到“宽”。两者都是必需的,因为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com