首页 > 解决方案 > 每天更新的文件上的 Pivot_longer

问题描述

尝试调整每天从网络上导入的 Covid-19 死亡数据框架(约翰霍普金斯大学数据)。当前文件有 414 列宽,每天增长一列。当我按列索引指定宽度时,Pivot_longer 有效,但在我尝试时触发错误last_col()

例如,这有效:

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

此代码(摘录)不:

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

我收到一条错误消息,提示无法识别术语“last_col()”。所以看起来我必须每天都去手动插入最后一列的索引。还是有更好的答案?

标签: rdplyrtidyr

解决方案


推荐阅读