【问题标题】:How to create a list of elements in columns based on another in R dataframe如何基于R数据框中的另一个创建列中的元素列表
【发布时间】:2021-10-16 01:49:17
【问题描述】:

我有一张这样的桌子:

col1 col2 col3
x 1 4
x 2 5
x 3 6
y 1 4
y 2 5
y 3 6

我想根据它们在第一列中对应的内容将第二列和第三列中的元素组合为一个列表,如下所示:

col1 col2 col3
x [1, 2, 3] [4, 5, 6]
y [1, 2, 3] [4, 5, 6]

我该怎么做呢?谢谢

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这个使用 dplyr 的解决方案返回值的列表(不确定您是否想要字符串或列表,但您示例中的括号让我认为您想要列表...)

    library(dplyr)
    df1 %>% 
      group_by(col1) %>% 
      summarise(across(, list))
    

    【讨论】:

      【解决方案2】:

      这行得通吗:

      library(dplyr)
      library(stringr)
      
      df %>% group_by(col1) %>% summarise(col2 = str_c('[',toString(col2),']'))
      # A tibble: 2 x 2
        col1  col2     
        <chr> <chr>    
      1 x     [1, 2, 3]
      2 y     [1, 2, 3]
      

      【讨论】:

        【解决方案3】:

        您可以通过tidyr::pivot_wider 做到这一点

        library(tidyr)
        
        df %>% 
          pivot_wider(id_cols = col1,
                      values_from = -col1,
                      values_fn = list)
        

        默认的values_fnlist,所以从技术上讲,这里不需要它,但为了抑制警告消息,我明确表示了。

        【讨论】:

          【解决方案4】:

          使用来自base Raggregate

          aggregate(.~ col1, df1, list)
            col1    col2    col3
          1    x 1, 2, 3 4, 5, 6
          2    y 1, 2, 3 4, 5, 6
          

          数据

          df1 <- structure(list(col1 = c("x", "x", "x", "y", "y", "y"), col2 = c(1L, 
          2L, 3L, 1L, 2L, 3L), col3 = c(4L, 5L, 6L, 4L, 5L, 6L)),
           class = "data.frame", row.names = c(NA, 
          -6L))
          

          【讨论】:

            猜你喜欢
            • 2022-01-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-12-06
            • 1970-01-01
            • 1970-01-01
            • 2022-11-18
            • 1970-01-01
            相关资源
            最近更新 更多