将长格式拆分为行,但重复项合并为以“;”分隔的字符串?

问题描述

假设我有一个数据框要拆分成几行。

temp = data.frame ( group=c('a','b','c'),fruits = c('apple','orange','none'),days=c('mon','tues','wed') )
reshape2::dcast(temp,days ~ group,value.var=c ( "fruits") )
  days     a      b    c
1  mon apple   <NA> <NA>
2 tues  <NA> orange <NA>
3  wed  <NA>   <NA> none

这很好,但是当我这样添加重复的行时。

temp = rbind ( temp,c('a','mon')  )

转换将失败,仅显示总数。我真正想要的是这样的东西。

 days     a      b    c
1  mon apple;orange   <NA> <NA>
2 tues  <NA> orange <NA>
3  wed  <NA>   <NA> none

谢谢!

解决方法

尝试此tidyverse解决方案。您可以使用paste0()汇总数据以获取适当的结构,以转换为宽格式:

library(tidyverse)
#Code
temp %>%
  group_by(group,days) %>%
  summarise(fruits=paste0(fruits,collapse = ';')) %>%
  pivot_wider(names_from = group,values_from=fruits)

输出:

# A tibble: 3 x 4
  days  a            b      c    
  <chr> <chr>        <chr>  <chr>
1 mon   apple;orange NA     NA   
2 tues  NA           orange NA   
3 wed   NA           NA     none