【问题标题】:last occurrence of particular value with if else statement by group使用 if else 语句按组最后出现的特定值
【发布时间】:2019-09-26 09:57:46
【问题描述】:

假设我有以下数据:

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 的指标变量。在with 出现之前可以有多个sus,如组a。如果free 在with 之前最后出现,则它为零。

期望的输出:

   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))

参考:

How to find the date after the last occurrence of a certain observation in R?

How to find the last occurrence of a certain observation in grouped data in R?

有什么建议吗?

【问题讨论】:

    标签: r group-by dplyr


    【解决方案1】:

    我们可以group_byx 并检查y 的last 值是否为"sus" 并且不是"sus" 的last 值是否为"with" 并为最后一行分配值1组的。

    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
    

    【讨论】:

    • 谢谢。如果一组只有一行并且其中包含sus,我会遇到问题。例如,如果您重新运行删除前 3 行的代码cf &lt;- cf[-c(1:3), ],我得到:Error: Column sus_with must be length 1 (the group size), not 0。请问您知道一个快速的解决方法吗?
    • @user63230 是的,也许用if,cf %&gt;% group_by(x) %&gt;% mutate(sus_with = if (any(y != 'sus') &amp; n() &gt; 1) as.integer(last(y) == 'sus' &amp; last(y[y != "sus"]) == 'with' &amp; row_number() == n()) else 0) 检查条件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多