R:通过不同数据表的COL设置数据表的顺序



我已经看到了按其中一列对数据表排序的示例,但是如何按不同数据表的列对数据表进行排序?例如,如果我有两个数据表:

x <- data.table(ID=1:3,A=letters[3:1])
y <- data.table(ID=1:3,B=letters[1:3])

我想根据y$B的顺序对x进行排序:

setorder(x,y$B)
Error in setorderv(x, cols, order, na.last) : 
  some columns are not in the data.table: $,y,B

排序x时如何引用y中的Col?

只需在表中添加B

x[ , B := y$B]
setorder(x, B)
merge(y, x, by.x = "B", by.y = "A")

最新更新