从给定的数据帧中,我try 获取Cat
,monthly_dates
,monthly_val
,然后计算quarter
,quarterly_months
,quarterly_values
mont_dates <- c("201401", "201402", "201403", "201404", "201405",
"201406", "201407", "201408", "201409", "201410", "201411", "201412")
cat <- c("new", "old", "undefined", "new", "old", "undefined", "undefined", "new", "old", "undefined", "new", "old")
mont_vals <- c(221, 433, 878, 455, 998, 797, 77, 3435, 868, 686, 868, 434)
ID <- c(1,2,3,4,5,6,7,8,9,10,11,12)
df <- data.frame(mont_dates, mont_vals, cat, ID)
Monthly_Qrt_vals <- function(df1) {
df1 %>%
mutate(mont_dates = ymd(paste0(mont_dates, "01"))) %>%
pivot_longer(cols = -c(ID, cat, mont_dates),
names_to = "monthly_dates",
values_to = "monthly_val") %>%
mutate(quarter = paste0(year(mont_dates), " Q", quarter(mont_dates))) %>%
arrange(mont_dates) %>%
group_by(quarter) %>%
summarise(quarterly_values = sum(monthly_val, na.rm = TRUE),
quarterly_months = n()) %>%
ungroup() %>%
select(monthly_dates, monthly_val, quarter, quarterly_months, quarterly_values)
}
result <- df %>% Monthly_Qrt_vals()
View(result)
在我得到的pivot_longer
中,有Error个错误monthly_dates
不存在.
我在这段代码中做错了什么?
Error in `select()`:
! Can't subset columns that don't exist.
✖ Column `monthly_dates` doesn't exist.
Expected Outcome个
从dataframe
生成列
Cat monthly_dates monthly_val quarter quarterly_months quarterly_values
个