6

I guess it is correlated to that story : Changing behaviour of stats::lag when loading dplyr package , but I've found some weird behaviour of lag function when I try to use the default = option.

Check the simple commands below

library(dplyr)

df = data.frame(mtcars)

df %>% mutate(lag_cyl = lag(cyl))
## it works with NA in first value (as expected)

df %>% mutate(lag_cyl = lag(cyl, default = 999))
## it works with a given value as default

df %>% mutate(lag_cyl = lag(cyl, default = cyl[1]))
## it DOESN'T WORK with the first value of the column as default

df %>% mutate(lag_cyl = dplyr::lag(cyl, default = cyl[1]))
## it works when specifying dplyr::

val = df$cyl[1]
df %>% mutate(lag_cyl = lag(cyl, default = val))
## it works when I assign the first value of the column to a variable name

Is it just a conflict between the stats and dplyr packages?

5
  • 1
    Bizarrely, the following works as well: df %>% mutate(lag_cyl = stats::lag(cyl, default = cyl[1]))
    – crazybilly
    Commented Nov 4, 2015 at 18:10
  • @crazybilly It doesn't return an error, indeed, but does it shift the cyl values by one position in the new lag_cyl column?
    – AntoniosK
    Commented Nov 4, 2015 at 18:14
  • 1
    Oh, you're right--it doesn't return the desired effect. That said, it's not returning the same error, so at least we know that's not what's happening when you leave the "dplyr::" part off.
    – crazybilly
    Commented Nov 4, 2015 at 18:17
  • 1
    This looks similar to this (closed) github issue - maybe try the dev version?
    – aosmith
    Commented Nov 4, 2015 at 21:12
  • This appears to work in version 0.7.4, I suggest this question be closed.
    – r2evans
    Commented Apr 26, 2018 at 19:33

1 Answer 1

3

I can confirm that df %>% mutate(lag_cyl = lag(cyl, default = cyl[1])) works in dplyr version 0.8.0.1.

If it worked when specifying dplyr::lag it suggests that another library was masking the function. Hmisc has a function called lag, and you may have loaded this library (or another one with a lag function) after loading dplyr.

1
  • I think this is what happened in my case too. Thank you!!
    – KarthikS
    Commented Sep 29, 2020 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.