【问题标题】:How to fill column based on previous value + value other column in R [duplicate]如何根据R中的先前值+值其他列填充列[重复]
【发布时间】:2019-09-12 13:47:12
【问题描述】:

我想填充一个新列,该列基于列本身的先前值(我设置为 1 的第一个值)和 event 的值。

test_model

Obs event enum
1056 1      1
1059 1      NA
1070 0      NA
1054 1      NA
1034 0      NA

这应该变成:

Obs event enum
1056 1      1
1059 1      2
1070 0      2
1054 1      3
1034 0      3

到目前为止,我已经尝试过lag()

test_model$enum <- mutate(test_model, enum = (lag(enum) + event))

但是,这会导致该列填充了 test_model (Obs) 中不同列的观察结果。

Obs event enum
1056 1      1056
1059 1      1059
1070 0      1070
1054 1      1054
1034 0      1034

知道这是怎么发生的吗? 我应该以什么方式实现我的目标?

【问题讨论】:

  • 您在寻找mutate(test_model, enum = cumsum(event))吗?

标签: r lag dplyr


【解决方案1】:

我认为您正在寻找 cumsum() 函数。

test_model <- data.frame(Obs = c(1056,1059,1070,1054,1034),
                     event = c(1,1,0,1,0))
test_model$enum <- cumsum(test_model$event)

#Or using the tidyverse
test_model <- test_model %>% mutate(enum = cumsum(event))

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2021-06-19
    • 2019-06-06
    • 2021-08-31
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    相关资源
    最近更新 更多