0

Trying to pivot a data frame of Covid-19 deaths imported each day from the web (Johns Hopkins data). The current file is 414 columns wide, growing by one column per day. Pivot_longer works when I specify the width by column index but triggers an error when I try last_col().

For example, this works:

CountyDeathsC <- CountyDeathsB %>% 
  pivot_longer(cols = c(4:414), names_to="Date", values_to="Cumulative Deaths") %>% 
  group_by(FIPS, Population, Combined_Key) %>% 
  mutate(Date = mdy(Date)) %>% 
  mutate(DeathsToday = `Cumulative Deaths` - dplyr::lag(`Cumulative Deaths`, 
                                                      n = 1, default = 0),
       Deaths7DayAvg = round(zoo::rollapplyr(DeathsToday, 7, mean, na.rm=TRUE, fill=NA))) %>% 
  mutate(CumDeathsPer100k = `Cumulative Deaths` / (Population / 100000))

This code (excerpt) does not:

pivot_longer(cols = c(4:last_col()), names_to="Date", values_to="Cumulative Deaths")

I get an error saying the term "last_col()" is not recognized. So it looks like I have to go in each day and manually insert the index for the last column. Or is there a better answer?

deschen
  • 10,012
  • 3
  • 27
  • 50

0 Answers0