在tidyr连接之后,根据原始数据帧对列进行排序

时间:2018-01-24 18:24:44

标签: r dplyr tidyr

在彼此进行两个数据帧的tidyr连接之后,如何根据它们来自的原始数据帧对返回的列进行排序?我在下面提出了几个解决方案。第一个感觉笨重。第二种可能不是很好的做法。我想我错过了什么。

library(tidyverse)

a <- data_frame(x1 = LETTERS[1:3], x2 = 1:3)
b <- data_frame(x1 = LETTERS[c(1,2,4)], x3 = c(TRUE, FALSE, TRUE))

# Not the order I want
left_join(a, b, by = "x1")

# This is the order I want
a %>%
  left_join(b, by = "x1") %>%
  select(names(b), names(a)[!(names(a) %in% names(b))])

# This works too.
right_join(b, a, by = "x1") 

1 个答案:

答案 0 :(得分:2)

我想你可以做unique(c(names(b), names(a)))

a %>%
    left_join(b, by = "x1") %>%
    select(unique(c(names(b), names(a))))

# A tibble: 3 x 3
#     x1    x3    x2
#  <chr> <lgl> <int>
#1     A  TRUE     1
#2     B FALSE     2
#3     C    NA     3