代码之家  ›  专栏  ›  技术社区  ›  labgeek

将数据帧及其组合名称的所有成对组合复制到新的数据帧中

  •  0
  • labgeek  · 技术社区  · 2 年前

    # dataframe with col names a1:a5
    df <- data.frame(a1 = c(4, 2, 6, 9, 13),
                     a2 = c(56, 1, 47, 2, 3),
                     a3 = c(4, 6, 9, 11, 85),
                     a4 = c(6, 15, 4, 12, 3),
                     a5 = c(54, 94, 3, 2, 75))
    
    # and with rownames a1:a5
    rownames(df) <- c("a1","a2","a3","a4","a5")
    

    df现在看起来像这样:

    a2 a3 a5
    a1 4. 6. 54
    2. 1. 94
    6. 47 4.
    9 2. 11 12
    13 3. 3.

    我需要一个包含所有可能组合的新数据帧(所以25x2),如下所示:

    1. a1a1
    2. a1a2
    3. a1a3 4.
    a1a4 6.
    ...
    a5a5 75

    非常感谢。

    2 回复  |  直到 2 年前
        1
  •  1
  •   s__    2 年前

    您可以将其放在长格式中:

    library(tidyr)
    library(dplyr)
     
     df %>%
      # add as column row names
      mutate(col1 = rownames(.)) %>%
      # from wide to long format
      pivot_longer( -col1, values_to = "Value", names_to = "col2") %>%
      # create the combination in the format you need
      mutate(step = paste0(col1,col2)) %>%
      # select useful columns
      select(step, Value) %>%
      # sort by step
      arrange(step)
    
    # A tibble: 25 x 2
       step  Value
       <chr> <dbl>
     1 a1a1      4
     2 a1a2     56
     3 a1a3      4
     4 a1a4      6
     5 a1a5     54
     6 a2a1      2
     7 a2a2      1
     8 a2a3      6
     9 a2a4     15
    10 a2a5     94
    # ... with 15 more rows
    
        2
  •  1
  •   Darren Tsai    2 年前

    您可以将数据转换为 table 回到a data.frame .

    df2 <- as.data.frame(as.table(as.matrix(df)))
    df2[order(df2$Var1), ]
    
    #    Var1 Var2 Freq
    # 1    a1   a1    4
    # 6    a1   a2   56
    # 11   a1   a3    4
    # 16   a1   a4    6
    # 21   a1   a5   54
    # 2    a2   a1    2
    # 7    a2   a2    1
    # 12   a2   a3    6
    # 17   a2   a4   15
    # 22   a2   a5   94
    # ...