在data.table

时间:2016-01-14 15:24:30

标签: r data.table cbind lexicographic

如何有效地将两个键控列绑定到单个列中,这将保留两个键的词典顺序? 我有兴趣将'loc'用作单个(已排序)变量

dt = data.table( 
  loc.x = as.integer(c(1, 1, 3, 1, 3, 1)),
  loc.y = as.integer(c(1, 2, 1, 2, 1, 2)),
  value = letters[1:6]
)
setkey(dt, loc.x, loc.y)

1 个答案:

答案 0 :(得分:0)

我不是你想要的,但是你可以将它们作为字符折叠并对它们进行排序,它们会给出1.1,1.2,1.3,......,2.1,2.2 ......

> loc.x = as.integer(c(1, 1, 3, 1, 3, 1))
> loc.y = as.integer(c(1, 2, 1, 2, 1, 2))
> x = cbind(loc.x,loc.y)
> sort(apply(x, 1, function(a) paste0(as.character(a), collapse = ".")))
[1] "1.1" "1.2" "1.2" "1.2" "3.1" "3.1"