【发布时间】:2017-02-08 18:33:06
【问题描述】:
我正在加入具有我不想想要加入的重复列的数据框(tibbles)。下面的例子是我通常会做的(通过i 加入,但不是a 或b):
library(dplyr)
df1 <- tibble(i = letters[1:3], a = 1:3, b = 4:6)
df2 <- tibble(i = letters[1:3], a = 11:13, b = 14:16)
d <- full_join(df1, df2, by ="i")
d
#> # A tibble: 3 × 5
#> i a.x b.x a.y b.y
#> <chr> <int> <int> <int> <int>
#> 1 a 1 4 11 14
#> 2 b 2 5 12 15
#> 3 c 3 6 13 16
我希望这些重复的变量以嵌套列表的形式返回,例如下面创建的输出:
tibble(
i = letters[1:3],
a = list(c(1, 11), c(2, 12), c(3, 13)),
b = list(c(4, 14), c(5, 15), c(6, 16))
)
#> # A tibble: 3 × 3
#> i a b
#> <chr> <list> <list>
#> 1 a <dbl [2]> <dbl [2]>
#> 2 b <dbl [2]> <dbl [2]>
#> 3 c <dbl [2]> <dbl [2]>
有没有简单的方法来做这样的事情?
除此之外,我一直在使用各种 stringr 和 tidyr 方法(但未成功)。这是一个引发错误的示例:
library(stringr)
library(tidyr)
# Find any variables with .x or .y
dup_var <- d %>% select(matches("\\.[xy]")) %>% names()
# Condense to the stems (original names) of these variables
dup_var_stems <- dup_var %>% str_replace("(\\.[x|y])+", "") %>% unique()
# For each stem, try to nest relevant data into a single variable
for (stem in dup_var_stems) {
d <- d %>% nest_(key_col = stem, nest_cols = names(d)[str_detect(names(d), paste0(stem, "[$|\\.]"))])
}
更新
在@Sotos 和@conor 的回答之后,我会提到解决方案需要推广到多个数据帧上的多个连接和重复列。下面是一个示例,其中通过两列(i 和j)对五个数据帧进行连接。这会创建五个重复版本的列a 和b,还有很多独特的列c:g。一个问题是复制这么多数据帧会导致复制的版本没有后缀,.x,.x.x,等等。如此简单的.x|.y 正则表达式匹配将错过该列的无后缀版本。
library(dplyr)
library(purrr)
id_cols <- tibble(i = c("x", "x", "y", "y"),
j = c(1, 2, 1, 2))
df1 <- id_cols %>% cbind(tibble(a = 1:4, b = 5:8, c = 21:24))
df2 <- id_cols %>% cbind(tibble(a = 2:5, b = 6:9, d = 31:34))
df3 <- id_cols %>% cbind(tibble(a = 2:5, b = 6:9, e = 31:34))
df4 <- id_cols %>% cbind(tibble(a = 2:5, b = 6:9, f = 31:34))
df5 <- id_cols %>% cbind(tibble(a = 2:5, b = 6:9, g = 31:34))
datalist <- list(df1, df2, df3, df4, df5)
d <- reduce(datalist, full_join, by = c("i", "j"))
d
#> i j a.x b.x c a.y b.y d a.x.x b.x.x e a.y.y b.y.y f a b g
#> 1 x 1 1 5 21 2 6 31 2 6 31 2 6 31 2 6 31
#> 2 x 2 2 6 22 3 7 32 3 7 32 3 7 32 3 7 32
#> 3 y 1 3 7 23 4 8 33 4 8 33 4 8 33 4 8 33
#> 4 y 2 4 8 24 5 9 34 5 9 34 5 9 34 5 9 34
【问题讨论】:
-
我认为您在尝试中遇到的错误有点奇怪。
nest已经有嵌套列的小标题应该没问题。你可能想举报。 -
谢谢@Axeman。我已将其缩减为从
nest()中排除列表变量。我已将此作为问题发布在 tidyr 存储库 github.com/hadley/tidyr/issues/249