【问题标题】:Generating a new variable if any of the conditions are met without list all variables in R如果满足任何条件而不列出 R 中的所有变量,则生成一个新变量
【发布时间】:2023-02-13 23:26:31
【问题描述】:

我想生成一个名为结果如果下面数据集中的任何列具有任何形式的同意响应,则分配 1,否则分配 0。但是,我不想在我的代码中列出所有变量。 我试过以下代码;

vars<-c("a1","a2","a3","a4")
dat<-dat%>% 
  mutate(outcome = case_when(if_any(vars, ~ .x == "consented now"|
                                            "consented later") ~ 1))

数据集

dat1 <- tibble(
  a1 = c("consented now", NA, NA, NA),
  a2= c("", "Refused", NA, NA),
  a3= c(NA, "consented now", NA, NA),
  a4= c(NA, NA, NA, "consented later"))

【问题讨论】:

    标签: r


    【解决方案1】:

    你不需要case_whenif_anygrepl

    dat1 %>% 
      mutate(outcome = +if_any(all_of(vars), ~ grepl("consented", .x)))
    

    输出

    # A tibble: 4 × 5
    #  a1            a2        a3            a4              outcome
    #  <chr>         <chr>     <chr>         <chr>             <int>
    #1 consented now ""        NA            NA                    1
    #2 NA            "Refused" consented now NA                    1
    #3 NA             NA       NA            NA                    0
    #4 NA             NA       NA            consented later       1
    

    【讨论】:

      【解决方案2】:

      A根据使用pastedo.callgrepl的变体可能是:

      dat1$outcome <- +grepl("consented", do.call(paste, dat1))
      
      dat1
      #             a1      a2            a3              a4 outcome
      #1 consented now                  <NA>            <NA>       1
      #2          <NA> Refused consented now            <NA>       1
      #3          <NA>    <NA>          <NA>            <NA>       0
      #4          <NA>    <NA>          <NA> consented later       1
      

      或者使用rowSumssapply

      dat1$outcome <- +(rowSums(sapply(dat1, grepl, pattern="consented")) > 0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        • 2022-11-24
        • 2021-07-16
        • 1970-01-01
        • 2021-02-09
        • 2012-08-06
        • 2023-03-15
        相关资源
        最近更新 更多