【问题标题】:Transpose R data frame and concatenate values that occur in multiple columns转置 R 数据框并连接出现在多列中的值
【发布时间】:2017-09-25 11:37:32
【问题描述】:

我需要将 R 中的数据框从以下内容转换:

id    past     present  future
id1   A        A        B
id2   B                 C
id3   A        C        
id4   B         B        A

到这里:

id    A              B              C
id1   past, present  future
id2                  past           future
id3   past                          present
id4   future         past, present

我尝试过使用 dcast,但我对 R 还很陌生,无法获得接近我需要的东西。我应该使用其他东西吗?

谢谢!

【问题讨论】:

    标签: r dataframe dcast


    【解决方案1】:

    我们可以gather它为'long'格式,按'id'、'val'、paste'key'元素组合在一起,spread它为'wide'

    library(tidyverse)
    gather(df1, key, val, -id) %>%
            filter(val !="") %>% 
            group_by(id, val) %>% 
            summarise(key = toString(key)) %>% 
            spread(val, key, fill = "")
    # A tibble: 4 x 4
    # Groups:   id [4]
    #     id             A             B       C
    # * <chr>         <chr>         <chr>   <chr>
    #1   id1 past, present        future        
    #2   id2                        past  future
    #3   id3          past               present
    #4   id4        future past, present        
    

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2021-11-22
      • 2022-08-20
      • 1970-01-01
      相关资源
      最近更新 更多