1

I have a data frame with data that looks like this that has 365 rows reflecting the calendar year. I am trying to shift the county name columns up by one row. The data frame doesn't contain any missing values.

enter image description here

I tried using the following code to shift it, but the resulting table has values that are all NA.

covid_shift <- covid_pivot %>% 
mutate(Maricopa = lag(Maricopa), Cook = lag(Cook), Harris = lag(Harris))

enter image description here

Does anyone know what might be the issue?

Phil
  • 7,287
  • 3
  • 36
  • 66
Tati16
  • 55
  • 5

1 Answers1

3

Since covid_pivot is grouped by date, and each of these groups has one row, the lead and lag functions return NA.

Try:

covid_shift <- covid_pivot %>%
  ungroup() %>%
  mutate(Maricopa = lag(Maricopa), Cook = lag(Cook), Harris = lag(Harris))

You might also consider using across()

covid_pivot %>%
  ungroup() %>%
  mutate(across(-date, ~lag(.x)))
langtang
  • 22,248
  • 1
  • 12
  • 27