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?
df %>% mutate(lag_cyl = stats::lag(cyl, default = cyl[1]))
cyl
values by one position in the newlag_cyl
column?