someguyinafloppyhat
someguyinafloppyhat

Reputation: 421

R: set order of data table by col of a different data table?

I've seen examples of sorting a data table by one of its columns, but how do I sort a data table by the column of a different data table? For example if I have two data tables:

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

I want to sort x based on the order of y$B:

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

How do I reference a col in y when sorting x?

Upvotes: 0

Views: 1840

Answers (2)

dracodoc
dracodoc

Reputation: 2763

merge(y, x, by.x = "B", by.y = "A")

Upvotes: 0

MichaelChirico
MichaelChirico

Reputation: 34763

Just add B to the table:

x[ , B := y$B]
setorder(x, B)

Upvotes: 4

Related Questions