【问题标题】:How to create combinations of values of one variable by group using tidyverse in R如何使用 R 中的 tidyverse 按组创建一个变量的值组合
【发布时间】:2020-11-18 15:19:32
【问题描述】:

我正在使用R 中的combn 函数来获取变量y 的值的所有组合,每次取2 个值,按x 的值分组。我预期的最终结果是 tibble 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)

【问题讨论】:

    标签: r combinations tidyverse


    【解决方案1】:

    试试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
      

      【讨论】:

        【解决方案3】:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-09
          • 2021-07-10
          • 1970-01-01
          • 2020-12-27
          • 2022-01-06
          • 2016-08-08
          • 2023-01-23
          • 2020-01-04
          相关资源
          最近更新 更多