Well, I know that there are already tons of related questions, but none gave an answer to my particular need.
I want to use dplyr "summarize" on a table with 50 columns, and I need to apply different summary functions to these.
"Summarize_all" and "summarize_at" both seem to have the disadvantage that it's not possible to apply different functions to different subgroups of variables.
As an example, let's assume the iris dataset would have 50 columns, so we do not want to address columns by names. I want the sum over the first two columns, the mean over the third and the first value for all remaining columns (after a group_by(Species)). How could I do this?
As other people have mentioned, this is normally done by calling
summarize_each
/summarize_at
/summarize_if
for every group of columns that you want to apply the summarizing function to. As far as I know, you would have to create a custom function that performs summarizations to each subset. You can for example set the colnames in such way that you can use the select helpers (e.g.contains()
) to filter just the columns that you want to apply the function to. If not, then you can set the specific column numbers that you want to summarize.For the example you mentioned, you could try the following:
You could summarise the data with each function separately and then join the data later if needed.
So something like this for the iris example:
Though I would try to think of something else if there are more than a handful of summarising functions you need to use.
Try this: