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

前端 未结 2 501
隐瞒了意图╮
隐瞒了意图╮ 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
    #*   <chr>             <chr>         <chr>  <chr>
    #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
    
    0 讨论(0)
  • 2021-01-14 18:21

    Something like this? If you have loads of columns.

    result<-with(new.env(),{
      Client<-c("Client1","Client2","Client3","Client4","Client5")
      Sex_M<-c("Male","NA","Male","NA","Male")
      Sex_F<-c(" ","Female"," ","Female"," ")
      Satisfaction_Satisfied<-c("Satisfied"," "," ","Satisfied","Satisfied")
      Satisfaction_VerySatisfied<-c(" ","VerySatisfied","VerySatisfied"," "," ")
      CommunicationType_Email<-c("Email"," "," ","Email","Email")
      CommunicationType_Phone<-c(" ","Phone ","Phone "," "," ")
      x<-ls()
      categories<-unique(sub("(.*)_(.*)", "\\1", x))
      df<-setNames(data.frame( lapply(x, function(y) get(y))), x)
      for(nm in categories){
        df<-unite_(df, nm, x[contains(vars = x, match = nm)])
      }
      return(df)
    })
    
    Client CommunicationType    Satisfaction       Sex
    1 Client1           Email_      Satisfied_      _Male
    2 Client2           _Phone   _VerySatisfied Female_NA
    3 Client3           _Phone   _VerySatisfied     _Male
    4 Client4           Email_      Satisfied_  Female_NA
    5 Client5           Email_      Satisfied_      _Male
    
    0 讨论(0)
提交回复
热议问题