Suppose, in the iris data set, that I want to:
- Order by
Speciesbased on a column containing the maximumSepal.Length, in descending order. - Remove the maximum
Sepal.Lengthcolumn. - Within each
Species, keeping the order from the first step above, orderSepal.Lengthin descending order.
The following code yields the desired output:
library(dplyr)
df <- iris %>%
group_by(Species) %>%
mutate(max.Sepal.length = max(Sepal.Length, na.rm = TRUE)) %>%
as.data.frame() %>%
arrange(desc(max.Sepal.length)) %>%
select(-max.Sepal.length)
df[,"Species"] <- factor(df[,"Species"],
levels = unique(df[,"Species"]),
ordered = TRUE)
df <- df %>%
arrange(Species, desc(Sepal.Length)) %>%
as.data.frame()
However, suppose instead that I want to write this as a function:
df_order <- function(df, group_col, value_col) {
df <- df %>%
group_by({{ group_col }}) %>%
mutate("max_{{value_col}}" := max({{value_col}}, na.rm = TRUE)) %>%
as.data.frame() %>%
arrange(desc("max_{{value_col}}")) %>%
select(-"max_{{value_col}}")
df[,"{{group_col}}"] <- factor(df[,"{{group_col}}"],
levels = unique(df[,"{{group_col}}"]),
ordered = TRUE)
df <- df %>%
arrange({{group_col}}, desc({{value_col}})) %>%
as.data.frame()
return(df)
}
df_order(iris, Species, Sepal.Length)
Alas, this doesn't work. Could someone point me to where my code is wrong? I am not extremely familiar with how dplyr has integrated with glue.