我在弄清楚如何在R中重新排列数据帧中的行时有些麻烦。
我有两个顺序不同的数据帧,并且两个数据帧都有一个标识倾斜的ID。现在,我想对数据帧1(ID 1)重新排序,使其与数据帧2(ID2)的顺序相同。
非常感谢。
[在数据帧2中创建一列升序整数以对顺序进行编码。然后将该列合并到数据框1并对其进行排序。
library(dplyr)
df1 <- tibble(
id = c(1, 2, 3),
col1 = c('a', 'b', 'c')
)
df2 <- tibble(
id = c(3, 1, 2),
col2 = c('c', 'a', 'b')
)
df2$ordering <- sequence(nrow(df2))
df1_ordered <- df1 %>%
left_join(df2, by = 'id') %>%
arrange(ordering)
我们可以使用match
匹配ID,然后根据其重新排序df1
。使用@Chris的数据
df1[match(df2$id, df1$id),]
# id col1
# <dbl> <chr>
#1 3 c
#2 1 a
#3 2 b