R数据表setkey - 错误:某些列不在数据表中。

3

我想使用data.table中的setkey与预定义列表idcategories,但是出现了错误信息:

> setkey(tr_id_cat_dt, id, categories)
Error in setkeyv(x, cols, verbose = verbose) : 
  some columns are not in the data.table: categories

我希望所有的 idcategories 元素都能作为键出现。

这是否可能?


idcategories 是值列表,例如:

categories = c(9115L, 9909L, 3203L, 5558L, 4401L, 1703L, 1726L, 3504L, 3509L, 
5122L, 5616L, 5619L, 2202L, 2119L, 6202L, 5824L, 799L, 4517L, 
7205L, 706L)


dput(head(tr_id_cat_dt))
structure(list(id = c(86246, 86246, 86246, 86246, 86246, 86246
    ), category = c(706L, 706L, 706L, 706L, 706L, 706L)), .Names = c("id", 
    "category"), sorted = c("id", "category"), class = c("data.table", 
    "data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x015424a0>)

setkey(tr_id_cat_dt, c("id", "categories"))能行吗?还是应该用setkeyv(tr_id_cat_dt, c("id", "categories")) - David Arenburg
1
展示 dput(head(tr_id_cat_dt))categories 是否是 data.table 中的一列? - Roland
1
看一下 dput 输出的结构:你的 categories 列实际上被称为 category - Scott Ritchie
@Scott Richie 是的,但我不想使用tr_id_cat_dt$category中的值,我想使用categories中的值作为键。 - Timothée HENRY
1
你只能使用 data.table 的一列作为键。 - Roland
显示剩余5条评论
1个回答

3

正如@Roland所指出的那样,您只能在data.table的列上设置键(即使是多个列)。

require(data.table)
DT = data.table(x = 1:2, y=3:4)
z = 5:6
setkey(DT, x) # works
setkey(DT, z) # doesn't
# Error in setkeyv(x, cols, verbose = verbose, physical = physical) : 
#   some columns are not in the data.table: z

setkey(DT[, z := z], z) # works

HTH


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接