转置R数据帧并连接多列中出现的值

时间:2017-09-25 11:37:32

标签: r dataframe dcast

我需要在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很新,并且无法得到任何接近我需要的东西。我应该使用其他东西吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以gather将其设为'长'格式,按'id','val',paste将'key'元素组合在一起,spread将其设为'wide'< / p>

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