【问题标题】:How can i LAG the previous value that meets a condition in other column (R)?我怎样才能滞后满足其他列(R)中条件的先前值?
【发布时间】:2021-07-03 22:16:43
【问题描述】:

我想返回每行的前一个值,而不是n = 1,前一个必须满足其他列的条件。在这种情况下,如果 Presence = 1。

具有预期结果的表格

谢谢!

【问题讨论】:

  • 滞后值是否应该按人分组?
  • 是的!它应该。
  • 图片不是共享数据/代码的正确方式。以更易于复制的可复制格式添加它们。阅读how to give a reproducible example
  • 类似于 Martin 的方法 - df %>% mutate(lag = replace(result, presence != 1, NA)) %>% group_by(person) %>% fill(lag) %>% mutate(lag = lag(lag))

标签: r lag


【解决方案1】:

您可以使用dplyrtidyr

library(dplyr)
library(tidyr)

data %>% 
  group_by(person, indicator = cumsum(presence)) %>% 
  mutate(expected_lag = ifelse(presence == 0, NA, presence * result)) %>% 
  fill(expected_lag, .direction = "down") %>% 
  group_by(person) %>% 
  mutate(expected_lag = lag(expected_lag)) %>% 
  select(-indicator) %>% 
  ungroup()

返回

# A tibble: 9 x 4
  person presence result expected_lag
  <chr>     <dbl>  <dbl>        <dbl>
1 Ane           1      5           NA
2 Ane           0      6            5
3 Ane           0      4            5
4 Ane           1      8            5
5 Ane           1      7            8
6 John          0      9           NA
7 John          1      2           NA
8 John          0      4            2
9 John          1      3            2

数据

为简化起见,我删除了 date 列。

structure(list(person = c("Ane", "Ane", "Ane", "Ane", "Ane", 
"John", "John", "John", "John"), presence = c(1, 0, 0, 1, 1, 
0, 1, 0, 1), result = c(5, 6, 4, 8, 7, 9, 2, 4, 3)), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L), spec = structure(list(
    cols = list(person = structure(list(), class = c("collector_character", 
    "collector")), presence = structure(list(), class = c("collector_double", 
    "collector")), result = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1L), class = "col_spec"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2023-01-25
    • 2018-12-13
    • 2022-10-06
    • 2022-11-15
    • 2020-09-08
    • 2016-07-23
    相关资源
    最近更新 更多