case_when函数中〜之后的条件项 [英] Conditional term after the `~` in a `case_when` function

查看:76
本文介绍了case_when函数中〜之后的条件项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to put a conditional term after the ~ in a case_when function. My example:

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_by x
  2. 计算列 y
  3. 中的组 b cumsum
  4. 获取该组(= b)的最后一个值(= 15),并且
  5. 将此值(= 15)放入列 y ,其中组为 a
  1. group_by x
  2. calculate cumsum for group b in column y
  3. take the last value (=15) of this group (=b) and
  4. put this value (=15) to column y where group is 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

非常感谢!!!!

推荐答案

在计算第二个 mutate 并使用 last ,条件是使用 x =="b"

Just add the ungroup() before you calculate the 2nd mutate and use last with condition to get the last y with x == "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软件包(v2.0.0)创建于2021-04-22 sup>

Created on 2021-04-22 by the reprex package (v2.0.0)

这篇关于case_when函数中〜之后的条件项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆