I have a dataframe summarized as pivot table and I want to add a row with the mean of each numeric column, and for the character column the row can be named as "mean"
the sample dataframe is below
dat <- c('2000-01-15','2003-01-15','2000-02-15',
'2003-02-15','2000-04-15','2002-04-15',
'2000-12-15','2002-12-15','2003-12-13', "2003-12-15",'2002-02-21','2002-01-25','2003-04-24')
df <- data.frame(date =as.Date(dat), id = c(1,2,3,4,5,6,7,8,9,10,11,12,13),
sales = c(134,211,2000,234,421,400,34,1233,1222,1034,8034,1234,2331))
df <- df %>%
mutate(year = format(date, "%Y"),
month = format(date, "%b")) %>% select(-date) %>%
group_by(year,month) %>%
summarise(revenue = sum(sales))
df2 <- df %>% pivot_wider(id_cols = year, names_from = month, values_from = revenue)
From here I want to do
rbind(df2, summarise_all(df2, mean))
However, the main complication is on how to return the mean of just the numeric column and return a character with non numeric column.
My desrired output should be
year Apr Dec Feb Jan
<chr> <dbl> <dbl> <dbl> <dbl>
1 2000 421 34 2000 134
2 2002 400 1233 8034 1234
3 2003 2331 2256 234 211
4 mean 1051. 1174. 3423. 526.