【问题标题】:Conditional term after the `~` in a `case_when` function`case_when` 函数中 `~` 之后的条件项
【发布时间】:2021-07-16 09:41:58
【问题描述】:

我想在 case_when 函数中的 ~ 之后放置一个条件项。 我的例子:

df:

df <- structure(list(x = c("a", "a", "a", "b", "b", "b", "c", "c", 
"c", "a", "a", "a"), y = 1:12), class = "data.frame", row.names = c(NA, 
-12L))

不工作的代码:

library(dplyr)
df %>% 
  group_by(x) %>% 
  mutate(y = case_when(x=="b" ~ cumsum(y),
                       TRUE ~ y)) %>% 
  mutate(y = case_when(x=="a" ~ "what I want: last value of group "b" in column y", 
                       TRUE ~ y))

言辞:

  1. group_byx
  2. y 列中为组@98​​7654328@ 计算cumsum
  3. 取该组 (=b) 的最后一个值 (=15) 并
  4. 将此值(=15)放入y 列,其中组为a

想要的输出:

   x         y
   <chr> <dbl>
 1 a        15
 2 a        15
 3 a        15
 4 b         4
 5 b         9
 6 b        15
 7 c         7
 8 c         8
 9 c         9
10 a        15
11 a        15
12 a        15

非常感谢!!!

【问题讨论】:

    标签: r dplyr tidyverse case-when


    【解决方案1】:

    在这种情况下,group_by() 不是必需的(尽管它有助于提高可读性等):

    df %>%
     mutate(y = case_when(x == "b" ~ cumsum(y * (x == "b")),
                          x == "a" ~ max(cumsum(y[x == "b"])),
                          TRUE ~ y))
    
       x  y
    1  a 15
    2  a 15
    3  a 15
    4  b  4
    5  b  9
    6  b 15
    7  c  7
    8  c  8
    9  c  9
    10 a 15
    11 a 15
    12 a 15
    

    【讨论】:

    • 在我的编码世界中更加轻松。伟大的 tmfmnk!
    【解决方案2】:

    只需在计算第二个mutate 之前添加ungroup() 并使用last 和条件来获得最后一个yx == "b"

    library(dplyr)
    
    df %>% 
      group_by(x) %>% 
      mutate(y = case_when(x=="b" ~ cumsum(y),
        TRUE ~ y)) %>% 
      # add the ungroup here
      ungroup() %>%
      # and then the value is like this
      mutate(y = case_when(x=="a" ~ last(y[x == "b"]), 
        TRUE ~ y))
    #> # A tibble: 12 x 2
    #>    x         y
    #>    <chr> <int>
    #>  1 a        15
    #>  2 a        15
    #>  3 a        15
    #>  4 b         4
    #>  5 b         9
    #>  6 b        15
    #>  7 c         7
    #>  8 c         8
    #>  9 c         9
    #> 10 a        15
    #> 11 a        15
    #> 12 a        15
    

    reprex package (v2.0.0) 于 2021-04-22 创建

    【讨论】:

    • 谢谢 Sinh,为了得到这部分而浪费了几个小时y[x == "b"]
    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2021-09-17
    • 2019-07-06
    • 2018-08-05
    相关资源
    最近更新 更多