【问题标题】:Produce all combinations of one element with all other elements within a single column in R在 R 的单个列中生成一个元素与所有其他元素的所有组合
【发布时间】:2021-06-06 19:00:11
【问题描述】:

假设我有一个包含字母 a、b、c、d、e 的单列的数据框。

a
b
c
d
e

在 R 中,是否可以提取单个字母,例如“a”,并生成“a”和其他字母之间所有可能的配对组合(没有重复)?在这种情况下可以使用combn 命令吗?

a b
a c
a d
a e

【问题讨论】:

    标签: r combn


    【解决方案1】:

    我们可以使用data.frame

    data.frame(col1 = 'a', col2 = setdiff(df1$V1, "a"))
    

    -输出

    col1 col2
    1    a    b
    2    a    c
    3    a    d
    4    a    e
    

    数据

    df1 <- structure(list(V1 = c("a", "b", "c", "d", "e")),
        class = "data.frame", row.names = c(NA, 
    -5L))
    
    

    【讨论】:

    • 出色的@akrun!您能简要解释一下 setdiff 命令在这里的作用吗?
    • @LyricalStats9 谢谢。 setdiff 从“V1”列的唯一元素中删除元素“a”
    【解决方案2】:

    更新: 使用.before=1 参数,代码更短:-)

    df %>% 
      mutate(col_a = first(col1), .before=1) %>%
      slice(-1)
    

    使用dplyr,您可以:

    library(dplyr)
    df %>% 
      mutate(col2 = first(col1)) %>%
      slice(-1) %>% 
      select(col2, col1)
    

    输出:

      col2  col1 
      <chr> <chr>
    1 a     b    
    2 a     c    
    3 a     d    
    4 a     e  
    

    【讨论】:

      【解决方案3】:

      你可以使用

      expand.grid(x=df[1,], y=df[2:5,])
      

      返回

        x y
      1 a b
      2 a c
      3 a d
      4 a e
      

      【讨论】:

        猜你喜欢
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多