使用with data.table

时间:2014-02-19 16:27:07

标签: r 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>)

1 个答案:

答案 0 :(得分:1)

我想我会关闭这个。如果遇到同样的问题,请运行str(x.small)并查看向量是否以“Named”开头,检查问题列是否为命名向量。出于某种原因,在对命名向量进行操作时使用by参数会导致问题。这似乎是早期版本的data.table中的一个小错误,它在更高版本中进行了修补。要解决此问题,请升级data.table或仅使用unname()作为@Frank建议:

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