Can you make dplyr::mutate and dplyr::lag default = its own input value?

前端 未结 3 1452
醉酒成梦
醉酒成梦 2021-01-06 02:01

This is similar to this dplyr lag post, and this dplyr mutate lag post, but neither of those ask this question about defaulting to the input value. I am using dplyr to muta

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 02:25

    In the OP's code ...

    ...
    d) group_by(ip) %>%
    e) mutate(shifted = dplyr::lag(fulldate, default=fulldate)) %>%
    ...
    

    The default= argument should have a length of one. Replacing the OP's code with default = first(fulldate) should work in this case (since the first element won't have a lag and so is where we need to apply the default value).

    Related cases:

    • Similarly, with a "lead", we'd want dplyr::lead(x, default=last(x)).
    • With a lag or lead of more than one step (n greater than 1), default= cannot do it and we'd probably need to switch to if_else or case_when or similar. (I'm not sure about the current tidyverse idiom.)

提交回复
热议问题