2017-09-25 28 views
1

我需要的東西在R鍵變換數據幀是這樣的:移調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 

我已經試過玩但是我對R很新,並且沒有能夠接近我需要的東西。我應該使用別的東西嗎?

謝謝!

回答

1

我們可以把它gather以 '長' 格式,由 'ID' 分組, 'VAL',paste的 '鑰匙' 元素結合在一起,它spread以 '寬'

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