在dplyr中使用正则表达式来缩短case_when

时间:2018-11-20 12:04:32

标签: r regex dplyr

我有一个case_when语句,它太长了,我认为使用列名上的正则表达式可以很容易地将其缩短

输入

de<- dd %>%
#Check that Fraction is % Time Spent in Reflux
mutate(
  AcidRefluxBRAVO = case_when(
    ReflDay1FractionTimepHLessThan4Supine  > 4.2        ~ "SupineAcid",
    ReflDay1NumberofRefluxesSupine  > 73 ~ "SupineAcid",
    ReflDay1FractionTimepHLessThan4Upright> 4.2        ~ "UprightAcid",
    ReflDay1NumberofRefluxesUpright > 73 ~ "UprightAcid",
    ReflDay1FractionTimepHLessThan4Total > 4.2        ~ "TotalAcid",
    ReflDay1NumberofRefluxesTotal > 73 ~ "TotalAcid",

    ReflDay2FractionTimepHLessThan4Supine > 4.2        ~ "SupineAcid",
    ReflDay2NumberofRefluxesSupine > 73 ~ "SupineAcid",
    ReflDay2FractionTimepHLessThan4Upright > 4.2        ~ "UprightAcid",
    ReflDay2NumberofRefluxesUpright > 73 ~ "UprightAcid",
    ReflDay2FractionTimepHLessThan4Total > 4.2        ~ "TotalAcid",
    ReflDay2NumberofRefluxesTotal > 73 ~ "TotalAcid",

    ReflDay3FractionTimepHLessThan4Supine > 4.2        ~ "SupineAcid",
    ReflDay3NumberofRefluxesSupine > 73 ~ "SupineAcid",
    ReflDay3FractionTimepHLessThan4Upright > 4.2        ~ "UprightAcid",
    ReflDay3NumberofRefluxesUpright > 73 ~ "UprightAcid",
    ReflDay3FractionTimepHLessThan4Total > 4.2        ~ "TotalAcid",
    ReflDay4NumberofRefluxesTotal > 73 ~ "TotalAcid",

    ReflDay4FractionTimepHLessThan4Supine > 4.2        ~ "SupineAcid",
    ReflDay4NumberofRefluxesSupine > 73 ~ "SupineAcid",
    ReflDay4FractionTimepHLessThan4Upright > 4.2        ~ "UprightAcid",
    ReflDay4NumberofRefluxesUpright > 73 ~ "UprightAcid",
    ReflDay4FractionTimepHLessThan4Total > 4.2        ~ "TotalAcid",
    ReflDay4NumberofRefluxesTotal > 73 ~ "TotalAcid",

    ReflDayTotalFractionTimepHLessThan4Supine > 4.2        ~ "SupineAcid",
    ReflDayTotalNumberofRefluxesSupine > 73 ~ "SupineAcid",
    ReflDayTotalFractionTimepHLessThan4Upright > 4.2        ~ "UprightAcid",
    ReflDayTotalNumberofRefluxesUpright > 73 ~ "UprightAcid",
    ReflDayTotalFractionTimepHLessThan4Total > 4.2        ~ "TotalAcid",
    ReflDayTotalNumberofRefluxesTotal > 73 ~ "TotalAcid",
    TRUE ~ "NoAcid"
  )
)

要使用的正则表达式:

 ReflDay\dNumber.*Supine
    ReflDay\dNumber.*Upright
    ReflDay\dNumber.*Total
    ReflDay\dFraction.*Supine
    ReflDay\dFraction.*Upright
    ReflDay\dFraction.*Total

但是,我不确定如何在case_when语句中的列名上使用正则表达式。

0 个答案:

没有答案