通过引用类似的列名将多列与Tidyr的联合组合

时间:2017-03-08 02:39:17

标签: r tidyr tidyverse

library(tidyr)
library(dplyr)
library(tidyverse)

以下是简单数据框的代码。我有一些杂乱的数据,导出列因子类别分布在不同的列。

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 "," "," ")
DF<-data_frame(Client,Sex_M,Sex_F,Satisfaction_Satisfied,Satisfaction_VerySatisfied,CommunicationType_Email,CommunicationType_Phone)

我想使用tidyr&#34;#34; unite&#34;将类别重新组合成单​​个列。

DF<-DF%>%unite(Sat,Satisfaction_Satisfied,Satisfaction_VerySatisfied,sep=" ")%>%
unite(Sex,Sex_M,Sex_F,sep=" ")

然而,我必须写多个&#34;联合&#34;我认为这违反了三次规则,因此必须有一种方法可以使这更容易,特别是因为我的真实数据包含需要组合的数十列。有没有办法使用&#34;联合&#34;一次但是以某种方式引用匹配的列名,以便所有相似的列名称(例如,包含&#34; Sex&#34; for&#34; Sex_M&#34;和&#34; Sex_F&#34;和& #34; CommunicationType&#34; for&#34; CommunicationType_Email&#34;和&#34; CommunicationType_Phone&#34;)与上述公式相结合?

我还想到了一个允许我输入列名的函数,但这对我来说太难了,因为它涉及复杂的标准评估。

2 个答案:

答案 0 :(得分:3)

我们可以使用unite

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

对于多个案例,也许

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

答案 1 :(得分:0)

这样的东西?如果你有很多列。

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