假设我有两个tibble:a
和b
。
a <- tibble("unordered_characters" = list( c("A","B"), c("X","Y") ) ,
"v" = c("G", "F"))
b <- tibble("unordered_characters" = list( c("B","A"), c("Y","X")),
"x" = c("M", "d"))
我想在a
上使用它们的公共变量加入b
,该变量是一个列表。但我希望列表是无序的,这样c("A","B")
应该与c("B","A")
相同。换句话说,setequal(c("A","B"),c("B","A"))
返回TRUE
。这将创建下表:
unordered_characters v x
------------------------
c("A","B") G M
c("X","Y") F d
但a %>% left_join(b)
导致以下结果:
unordered_characters v x
------------------------
c("A","B") G NA
c("X","Y") F NA
我该怎么解决这个问题?
在加入之前,我们可以使用map
在list
和sort
上循环
library(dplyr)
library(purrr)
a %>%
mutate(unordered_characters = map(unordered_characters, sort)) %>%
left_join(b %>%
mutate(unordered_characters = map(unordered_characters, sort)))
# A tibble: 2 x 3
# unordered_characters v x
# <list> <chr> <chr>
#1 <chr [2]> G M
#2 <chr [2]> F d