簡體   English   中英

與data.table一起使用

[英]Using by with data.table

在這里,我嘗試使用data.table中的by參數對每個組中的預測列進行排名。 我無法理解為什么以下代碼無法正常工作:

> x.small
       prediction group
 1: -0.0093753015    up
 2:  0.0204832283  down
 3: -0.0091790179  down
 4: -0.0473988803  down
 5:  0.0144955868  down
 6: -0.0139455871  down
 7:  0.0005746896    up
 8: -0.0174406693  down
 9: -0.0180556244  down
10: -0.0343069464    up
> x.small[, rank(prediction), by=group]
Error in rank(prediction) :
  'names' attribute [7] must be the same length as the vector [3]

但是此示例代碼可以正常工作:

> diamonds.dt <- data.table(diamonds[1:10, c('carat', 'color')])
> diamonds.dt
    carat color
 1:  0.23     E
 2:  0.21     E
 3:  0.23     E
 4:  0.29     I
 5:  0.31     J
 6:  0.24     J
 7:  0.24     I
 8:  0.26     H
 9:  0.22     E
10:  0.23     H
> diamonds.dt[, rank(carat), by=color]
    color  V1
 1:     E 3.5
 2:     E 1.0
 3:     E 3.5
 4:     E 2.0
 5:     I 2.0
 6:     I 1.0
 7:     J 2.0
 8:     J 1.0
 9:     H 2.0
10:     H 1.0

任何幫助將非常感激!

編輯:

好吧,現在我真的不知道發生了什么,這很奇怪。 我嘗試為@Ananda制作一個可復制的示例,但無法重新創建該錯誤。 我什至嘗試在預測列的精確副本上運行排名邏輯,但效果很好:

> x.small[, prediction.copy:=prediction]
> x.small[, rank(prediction.copy), by=group]
    group V1
 1:    up  2
 2:    up  3
 3:    up  1
 4:  down  7
 5:  down  5
 6:  down  1
 7:  down  6
 8:  down  4
 9:  down  3
10:  down  2
> x.small[, rank(prediction), by=group]
Error in rank(prediction) :
  'names' attribute [7] must be the same length as the vector [3]

兩個相同的列怎么會有兩個不同的結果?

編輯2:

dput(x.small)的輸出:

> dput(x.small)
structure(list(prediction = structure(c(-0.00937530151309606,
0.0204832283018108, -0.00917901792827827, -0.0473988802836657,
0.0144955868466372, -0.0139455871394683, 0.000574689607249577,
-0.0174406692627376, -0.0180556244204637, -0.0343069463869563
), .Names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
)), group = c("up", "down", "down", "down", "down", "down", "up",
"down", "down", "up"), prediction.copy = c(-0.00937530151309606,
0.0204832283018108, -0.00917901792827827, -0.0473988802836657,
0.0144955868466372, -0.0139455871394683, 0.000574689607249577,
-0.0174406692627376, -0.0180556244204637, -0.0343069463869563
)), .Names = c("prediction", "group", "prediction.copy"), row.names = c(NA,
-10L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x22f2af8>)

我想我將關閉這個。 如果您遇到相同的問題,請通過運行str(x.small)並查看向量是否以單詞“ Named”開頭來檢查問題列是否為命名向量。 由於某些原因,在對命名向量進行操作時使用by參數會導致問題。 這似乎是data.table早期版本中的一個小錯誤,該錯誤已在更高版本中進行了修補。 要解決此問題,請升級data.table或按照@Frank的建議使用unname()

x.small[,rank(unname(prediction)), by=group]

暫無
暫無

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

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