5

I am using dplyr in R (with great joy) and want to get the differential of the columns mpg to gear in mtcars. The first row then returns NA (for obvious reason). Instead of this first row being NA I would like it to stay the original value.

I am looking for a clean and efficient way to achieve this (not using join to add the first row to the differntiated values since the code on my own dataset contains many filters and grouped variables).

my code is as follows:

mtcars %>% mutate_at(vars(mpg:gear), funs(. - lag(., 1)))

I expect the first row to be mtcars[1] and the rest to be the differential

1 Answer 1

5

We can specify the default parameter with 0, otherwise, it would be NA

library(dplyr)
mtcars %>%
   mutate_at(vars(mpg:gear), list(~ . - lag(., default = 0)))

Or another option is diff with concatenating the first element

mtcars %>%
    mutate_at(vars(mpg:gear), list(~ c(first(.), diff(.))))

NOTE: The funs is getting deprecated. Instead of that we are using list

5
  • Thanks for the really quick reply. I think we are almost there. the differential would then be: mtcars %>% + mutate_at(vars(mpg:gear), list(~ . - lag(., default = first(.)))) but this gives zeros on the first row and not the orignal values of the first row Commented May 20, 2019 at 13:58
  • @JelleJansen Sorry didn't see that part. Fixed
    – akrun
    Commented May 20, 2019 at 13:59
  • sorry Akrun I added one thing to the comment, it gives zeros for the first row Commented May 20, 2019 at 14:12
  • 1
    @JelleJansen If you need the first elemen as such, then specify default as 0 so that any number - 0 = anynumber. I was earlier thinking about using that without the difference
    – akrun
    Commented May 20, 2019 at 14:13
  • Perfect @akran, library(dplyr) mtcars %>% mutate_at(vars(mpg:gear), list(~ . - lag(., default = first(-0)))) works! Commented May 20, 2019 at 15:29

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.