I have read the following threads that seem to be similar (but still different) questions with mine:
- Order data frame rows according to a target vector that specifies the desired order
- How to reorder data.table columns (without copying)
my questions are different because in thread 1, the two tables have same length, and i tried using method indicated in thread 2, but seems like they also have to be same length.
for illustration purpose, i'll create two tables as following:
table1 = data.frame(rbind(c(rep(c(TRUE,FALSE), 3)), c(rep(TRUE, 4), rep(FALSE, 2))))
dim(table1)
setnames(table1, letters[1:6])
table1
a b c d e f
1 TRUE FALSE TRUE FALSE TRUE FALSE
2 TRUE TRUE TRUE TRUE FALSE FALSE
table2 = data.frame(rbind(c(rep(c(TRUE,FALSE), 2)), c(rep(TRUE, 3), rep(FALSE, 1))))
dim(table2)
setnames(table2, letters[7:4])
table2
g f e d
1 TRUE FALSE TRUE FALSE
2 TRUE TRUE TRUE FALSE
the desired return would be:
f e d
1 FALSE TRUE FALSE
2 FALSE FALSE TRUE
the return table will fit the following criteria:
- contains ONLY the letters exist in BOTH tables
- order of the return table is consistent with the order in table 2
Basically, I want to clean my table1 to contain only column names that also exist in table2, and i want the table1 columns to be reordered in order same as the columns in table 2.
Let me know if I need to clarify anything else! Thank you!