【问题标题】:lag() not picking up the integer value in the previous rowlag() 没有拾取上一行中的整数值
【发布时间】:2019-07-29 21:44:15
【问题描述】:

我有一个与我在这里使用的结构相同的示例数据框:

df <- data.frame(cond_row = c(rep("no", 10), "yes", 
                              rep("no", 5), "yes", rep("no", 7)), 
                 count_row = 0, stringsAsFactors = FALSE)

df <- df %>% 
  mutate(count_row = ifelse(cond_row == "yes", 
                            lag(count_row) + 1, 
                            lag(count_row)))

我正在尝试使 count_row 列值在每次 cond_row 中的条件等于“yes”时添加一个,然后让它保持这种状态直到条件再次等于“yes”,然后再添加一个, 等等。在这种情况下,count_row 列应该是 10 个 0、6 个 1 和 7 个 2。问题是 lag() 正确地选择了 ifelse() 中的“是”条件,而不是“否”条件。因此,对于 cond_row 等于“yes”的行,count_row 列的值为 1,但当 cond_row 等于“no”时保持为 0。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以在逻辑表达式上使用cumsum,它会在 'cond_row' 中的每个“yes”实例增加 1 并保持该值直到它遇到下一个“yes”

    library(dplyr)
    df %>% 
       mutate(count_row = cumsum(cond_row == 'yes'))
    #   cond_row count_row
    #1        no         0
    #2        no         0
    #3        no         0
    #4        no         0
    #5        no         0
    #6        no         0
    #7        no         0
    #8        no         0
    #9        no         0
    #10       no         0
    #11      yes         1
    #12       no         1
    #13       no         1
    #14       no         1
    #15       no         1
    #16       no         1
    #17      yes         2
    #18       no         2
    #19       no         2
    #20       no         2
    #21       no         2
    #22       no         2
    #23       no         2
    #24       no         2
    

    base R

    df$count_row <- cumsum(df$cond_row == 'yes')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2018-01-01
      • 2018-12-01
      • 2015-01-10
      相关资源
      最近更新 更多