SiH
SiH

Reputation: 1546

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))


Upvotes: 0

Views: 36

Answers (2)

akrun
akrun

Reputation: 887118

We can use base R

tbl$evening <- c(tbl$morning[-1], NA)

Upvotes: 1

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

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)

Upvotes: 1

Related Questions