Combining Multiple Columns with Tidyr's Unite by Referencing Similar Column Names

前端 未结 2 504
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 17:48
library(tidyr)
library(dplyr)
library(tidyverse)

Below is the code for a simple dataframe. I have some messy data that was exported with column fac

2条回答
  •  别那么骄傲
    2021-01-14 18:18

    We can use unite

    library(tidyverse)
    DF %>% 
        unite(Sat, matches("^Sat"))
    

    For multiple cases, perhaps

    gather(DF, Var, Val, -Client, na.rm = TRUE) %>%
            separate(Var, into = c("Var1", "Var2")) %>%
            group_by(Client, Var1) %>% 
            summarise(Val = paste(Val[!(is.na(Val)|Val=="")], collapse="_")) %>%
            spread(Var1, Val)
    #  Client CommunicationType  Satisfaction    Sex
    #*                           
    #1 Client1             Email     Satisfied   Male
    #2 Client2             Phone VerySatisfied Female
    #3 Client3             Phone VerySatisfied   Male
    #4 Client4             Email     Satisfied Female
    #5 Client5             Email     Satisfied   Male
    

提交回复
热议问题