【问题标题】:Stacking columns to make more rows in DPLYR堆叠列以在 DPLYR 中创建更多行
【发布时间】:2022-01-16 03:19:46
【问题描述】:

如何在 dplyr 中转换这个输入 df

     new_s1 new_d1 new_e1     new_s2 new_d2 new_e2
1         A     ->      L          D     ->      L
2         D     ->      L          D     ->      L
3         K     ->      L          A     ->      L

输出到这个预期的输出,我将前三列与最后三列堆叠在一起,并进行一些列名更改

          s      d      e     
1         A     ->      L
2         D     ->      L
3         D     ->      L          
4         D     ->      L
5         K     ->      L          
6         A     ->      L

我假设我应该使用 pivot_longer() ?但我想不出解决办法。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    使用pivot_longer,您可以使用names_pattern 来包含要从列名中提取的模式。对于共享的示例,您可以使用 -

    tidyr::pivot_longer(df, 
                 cols = everything(), 
                 names_to = '.value', 
                 names_pattern = 'new_(\\w)\\d+')
    
    #   s     d     e    
    #  <chr> <chr> <chr>
    #1 A     ->    L    
    #2 D     ->    L    
    #3 D     ->    L    
    #4 D     ->    L    
    #5 K     ->    L    
    #6 A     ->    L    
    

    数据

    df <- structure(list(new_s1 = c("A", "D", "K"), new_d1 = c("->", "->", 
    "->"), new_e1 = c("L", "L", "L"), new_s2 = c("D", "D", "A"), 
        new_d2 = c("->", "->", "->"), new_e2 = c("L", "L", "L")), 
    class = "data.frame", row.names = c(NA, -3L))
    

    【讨论】:

      【解决方案2】:

      dplyr 唯一的解决方案:

      library(dplyr)
      
      df %>% 
        select(1:3) %>% 
        bind_rows(df[4:6] %>% 
                    `colnames<-` (colnames(df[1:3]))) %>% 
        rename_with(~substr(.,5,5)) %>% 
        as_tibble()
      
        s     d     e    
        <chr> <chr> <chr>
      1 A     ->    L    
      2 D     ->    L    
      3 K     ->    L    
      4 D     ->    L    
      5 D     ->    L    
      6 A     ->    L    
      

      【讨论】:

        【解决方案3】:

        base Rsplit.default 一起使用

        out <- data.frame(lapply(split.default(df, trimws(names(df),
                  whitespace = ".*_|\\d+")), unlist))
        row.names(out) <- NULL
        

        -输出

        out
           d e s
        1 -> L A
        2 -> L D
        3 -> L K
        4 -> L D
        5 -> L D
        6 -> L A
        

        【讨论】:

          猜你喜欢
          • 2023-01-02
          • 2021-02-24
          • 1970-01-01
          • 2020-06-25
          • 1970-01-01
          • 1970-01-01
          • 2020-11-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多