Search code examples
rdplyrtibble

Seeking help in mutate in tibble


I have inventory of an item at the start of each day stored in tibble with column name - morning. I want to create another column (evening) which will have inventory at the end of the day (same as the inventory in next morning).

Can someone please correct my code below -

library(dplyr)

tbl <- tibble(morning = 5:10:95)

tbl <- tbl %>%
mutate(evening = c(morning[2, nrow(tbl)], NULL))



Solution

  • Use the function lead:

    tbl %>%
      mutate(evening = lead(morning))
    # A tibble: 6 x 2
      morning evening
        <int>   <int>
    1       5       6
    2       6       7
    3       7       8
    4       8       9
    5       9      10
    6      10      NA
    

    Test data:

    tbl <- tibble(morning = 5:10)