如何使用tidyverse在R中按组创建一个变量的值的组合?

4

我正在使用Rcombn函数获取变量y的每个值组合,并每次取2个值,然后根据变量x进行分组。 我期望的最终结果是表格c

但是当我尝试在tidyverse中实现它时出现了一些(非常)错误的情况。

library(tidyverse)

df <- tibble(x = c(1, 1, 1, 2, 2, 2, 2),
             y = c(8, 9, 7, 3, 5, 2, 1))


# This is what I want
a <- combn(df$y[df$x == 1], 2)
a <- rbind(a, rep(1, ncol(a)))


b <- combn(df$y[df$x == 2], 2)
b <- rbind(b, rep(2, ncol(b)))

c <- cbind(a, b)
c <- tibble(c)
c <- t(c)


# but using tidyverse it does not work
df %>% group_by(x) %>% mutate(z = combn(y, 2))
#> Error: Problem with `mutate()` input `z`.
#> x Input `z` can't be recycled to size 3.
#> i Input `z` is `combn(y, 2)`.
#> i Input `z` must be size 3 or 1, not 2.
#> i The error occurred in group 1: x = 1.
Created on 2020-11-18 by the reprex package (v0.3.0)
3个回答

2

尝试使用combn函数

out = df %>% group_by(x) %>% do(data.frame(t(combn(.$y, 2))))
# A tibble: 9 x 3
# Groups:   x [2]
      x    X1    X2
  <dbl> <dbl> <dbl>
1     1     8     9
2     1     8     7
3     1     9     7
4     2     3     5
5     2     3     2
6     2     3     1
7     2     5     2
8     2     5     1
9     2     2     1

2
如果您有 dplyr v1.0.2,您可以这样做。
df %>% group_by(x) %>% group_modify(~as_tibble(t(combn(.$y, 2L))))

输出

# A tibble: 9 x 3
# Groups:   x [2]
      x    V1    V2
  <dbl> <dbl> <dbl>
1     1     8     9
2     1     8     7
3     1     9     7
4     2     3     5
5     2     3     2
6     2     3     1
7     2     5     2
8     2     5     1
9     2     2     1

1
一个使用 summariseunnest 的选项。
library(dplyr)
library(tidyr)
df %>% 
    group_by(x) %>% 
    summarise(y = list(as.data.frame(t(combn(y, 2)))), .groups = 'drop') %>% 
    unnest(c(y))
# A tibble: 9 x 3
#      x    V1    V2
#  <dbl> <dbl> <dbl>
#1     1     8     9
#2     1     8     7
#3     1     9     7
#4     2     3     5
#5     2     3     2
#6     2     3     1
#7     2     5     2
#8     2     5     1
#9     2     2     1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接