通过组if else语句最后一次出现特定值 [英] last occurrence of particular value with if else statement by group

查看:103
本文介绍了通过组if else语句最后一次出现特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有以下数据:

library(tidyverse)
cf <- data.frame(x = c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c", "d", "d", "e", "e"), 
            y = c("free", "with", "sus", "sus", "free", "with", "free", "sus", "sus", "with", "free", "sus", "free", "free", "with", "sus"))
> cf
   x    y
1  a free
2  a with
3  a  sus
4  a  sus
5  b free
6  b with
7  b free
8  b  sus
9  c  sus
10 c with
11 c free
12 c  sus
13 d free
14 d free
15 e with
16 e  sus

如果按组分组的y的最后一个值等于sus并且sus之前的最后一个值是with,则我希望获得等于1的指标变量.如组a中一样,在with出现之前可以有多个sus.如果free最后出现在with之前,则为零.

I want to obtain an indicator variable equal to 1 if the last value of y by group is equal to sus and the last value before sus was with. There can be a multiple sus before with occurs as in group a. If free occurs last first before with then its zero.

所需的输出:

   x    y sus_with
1  a free        0
2  a with        0
3  a  sus        0
4  a  sus        1
5  b free        0
6  b with        0
7  b free        0
8  b  sus        0
9  c  sus        0
10 c with        0
11 c free        0
12 c  sus        0
13 d free        0
14 d free        0
15 e with        0
16 e  sus        1 

我在想这样的事情:

cf %>%
  group_by(x) %>%
  mutate(sus_with = if_else(row_number() == n() & y == "sus" & last(y == "with" & y != "free"), 1, 0))

裁判:

如何找到R中某个观测值最后一次出现之后的日期?

如何在R中的分组数据中找到某个观测值的最后一次出现?

有什么建议吗?

推荐答案

我们可以group_by x并检查ylast值是否为"sus",以及last值是否不是"sus""with",并为组的最后一行分配值1.

We can group_by x and check if last value of y is "sus" and the last value which is not "sus" is "with" and assign value 1 for the last row of the group.

library(dplyr)

cf %>%
  group_by(x) %>%
  mutate(sus_with = as.integer(last(y) == 'sus' & last(y[y != "sus"]) == 'with' 
                     & row_number() == n()))

#    x     y     sus_with
#   <fct> <fct>    <int>
# 1 a     free         0
# 2 a     with         0
# 3 a     sus          0
# 4 a     sus          1
# 5 b     free         0
# 6 b     with         0
# 7 b     free         0
# 8 b     sus          0
# 9 c     sus          0
#10 c     with         0
#11 c     free         0
#12 c     sus          0
#13 d     free         0
#14 d     free         0
#15 e     with         0
#16 e     sus          1

这篇关于通过组if else语句最后一次出现特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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