如果我有一个需要反引号的列名,因为它包含逗号,setkey
则会抛出一个错误,提示不要使用逗号。该错误将我引向?setkey
但我在那里的示例中没有看到任何提到这一点的内容。我能找到的唯一解决方法是重命名该列,setkey
然后重命名。
示例代码:
library(data.table)
> DT = data.table(`X, in $` = rnorm(10))
> DT
X, in $
1: -1.28475886
2: 0.97789059
3: -0.05023914
4: -0.38133978
5: -0.24949607
6: 0.99213156
7: -0.29310512
8: 0.02840372
9: 0.25294231
10: -0.88955013
> setkey(DT, `X, in $`)
Error in setkeyv(x, cols, verbose = verbose) :
Don't use comma inside quotes. Please see the examples in help('setkey')
编辑:显示一个更可能的例子
对我来说,您遇到此问题的主要原因是在使用reshape2
dcast
字符列值(将来自外部源,例如数据库)并将它们设为列名之后。
只要您不需要键的“加入”行为,而只是想排序,那么您可以通过复制表来解决这个问题,或者data.frame
改用它。例如:
library(ggplot2)
library(reshape2)
DT = data.table(Office = rep(c("Cambridge, UK", "Cambridge, US", "London", "New York"), each = 12), Product = rep(1:12,4), Sales = rnorm(48)^2)
DF = dcast(DT, Product~Office)
DT = data.table(DF)
setkey(DT, 'Cambridge, UK')
DT = DT[order(DF$`Cambridge, UK`),]
DT
产生:
> library(ggplot2)
> library(reshape2)
>
> DT = data.table(Office = rep(c("Cambridge, UK", "Cambridge, US", "London", "New York"), each = 12), Product = rep(1:12,4), Sales = rnorm(48)^2)
> DF = dcast(DT, Product~Office)
Using Sales as value column: use value.var to override.
> DT = data.table(DF)
> setkey(DT, 'Cambridge, UK')
Error in setkeyv(x, cols, verbose = verbose) :
Don't use comma inside quotes. Please see the examples in help('setkey')
> DT = DT[order(DF$`Cambridge, UK`),]
> DT
Product Cambridge, UK Cambridge, US London New York
1: 12 0.0009257347 1.7183751269 0.818101229 0.002499808
2: 1 0.0010855828 0.0889560105 0.083778108 1.451149328
3: 2 0.0139649148 0.7385617360 0.221688602 4.771307440
4: 5 0.0520875574 0.3389613574 0.934932759 0.127634044
5: 10 0.0837778446 0.0598955035 0.015930174 0.715849795
6: 9 0.0856246191 1.1303900183 1.555058058 0.367063297
7: 6 0.1608235273 0.7147643550 0.004588596 2.995598768
8: 8 0.4797866129 0.1783997616 0.016459971 0.497328990
9: 4 0.5282546636 1.7011670679 0.016126768 0.024388172
10: 7 0.5655147714 0.1106522938 0.045130643 0.442473457
11: 3 0.8315246051 0.1399159784 5.792956446 1.632060601
12: 11 3.9958208033 0.0005297928 0.003282897 1.635506818