【问题标题】:case_when with multiple inner cases in Rcase_when 在 R 中有多个内部案例
【发布时间】:2022-06-10 18:48:10
【问题描述】:

我想在dplyr 管道中编写case_when 代码。但是,我正在尝试在其中添加多个案例。

例如:如果一个有如下数据框

id purchases
a need
a want
a none
b want
b need
c need
c need
c want
d none
d none

我想总结输出,以便需要每个 id 的前 2 个观察值的情况以及不考虑观察值“无”的情况,然后将 yes 放入新列中。如果不需要或不需要给定的 id,则 none,否则 no

输出应该如下:

id output
a no
b no
c yes
d none

我的代码

actions %>% group_by (id) %>% arrange(id) 
%>% summarise(output = case_when(first(purchases) == "need" & nth(purchases,2) =="need"~ "yes", "no"

我知道代码有点乱,因为我不知道当案例会导致yesno 时忽略none 观察的第二个条件是谁加起来

【问题讨论】:

    标签: r dplyr case


    【解决方案1】:

    我尝试将您的逻辑放在一个小函数f() 中,然后id 可以将其应用于purchases

    f <- function(p) {
      if(p[1]==p[2] & (p[1] %in% c("need", "want"))) return("yes")
      ifelse(all(p=="none"), "none", "no")
    }
    df %>% group_by(id) %>% summarize(output=f(purchases))
    

    输出

      id    output
      <chr> <chr> 
    1 a     no    
    2 b     no    
    3 c     yes   
    4 d     none 
    

    该函数检查购买的第一个和第二个值是否相等,以及它们是need 还是want;如果是,则返回“是”。否则,如果所有purchases 值都是“none”,则返回“none”,否则返回“no”。

    【讨论】:

      【解决方案2】:

      尝试此操作以从 purchases 顶部排除 none

      fun <- function(x){
        if(all(x == "none")) return("none")
        for(i in 1:(length(x)-2)){
          if(x[1] == "none") x <- x[2:length(x)]
        }
        if(x[1] == x[2]) return("yes")
        else return("no")
      }
      
      df %>% group_by(id) %>%
         summarise(output = fun(purchases))
      
      

      【讨论】:

      • 谢谢!我正在寻求的是,如果购买的 id 是(无,需要,需要)这样的顺序,输出将是“是”,因为我只会考虑需要和想要的顺序,而不考虑 none 值。通过这样做,我应该将 2 个需求算作我做出决定的输出 1 和输出 2。这段代码能满足这个要求吗?
      • 试试这个更新的代码
      • 不幸的是,它仍然没有解决目标情况下的情况,例如第一次购买是无但随后是 2 个需求,在这种情况下,输出将为是,但代码返回一个否。我尝试将case_when 中的条件作为case_when(purchases %in% c("need","want") &amp; purchases[[1]]=="need" &amp; purchases[[1]]==purchases[[2]])~"yes" 开始,然后继续执行您编写的其他两个部分,但是,它返回了一个长列表,其中 id 重复多次而不被分组..
      • 上次更新怎么样
      猜你喜欢
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2018-05-27
      • 2020-08-30
      • 2022-06-29
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多