簡體   English   中英

為什么不能在`dcast`中有幾個`value.var`?

[英]Why can't one have several `value.var` in `dcast`?

為什么不能在一個有多個變量傳遞給value.vardcast 來自?dcast

value.var存儲值的列的名稱,請參閱guess_value以了解默認策略。

它沒有明確指出只能將一個變量作為值傳遞給它。 但是,如果我嘗試,那么我得到一個錯誤:

> 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等)?

這個問題與你今天早些時候的其他問題非常相關。

@beginneR在評論中寫道:“只要現有數據已經​​采用長格式,我認為在投射之前我不需要融化它。” 在我的另一個問題的答案中,我給出了一個例子,說明何時需要melt ,或者更確切地說,如何確定您的數據是否足夠長。

這里的這個問題是另一個需要進一步melt例子,因為我的答案中的第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,然后使用reshapedcast從“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

我有同樣的問題,我找到了這個答案: 使用帶有多個value.var的dcast時出錯 ,建議“強制”data.table dcast函數如下:

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

我能夠無錯誤地投射多個變量。

嘗試使用setDT或as.data.table將data.frame強制轉換為data.table。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM