Suppose, in the iris
data set, that I want to:
- Order by
Species
based on a column containing the maximumSepal.Length
, in descending order. - Remove the maximum
Sepal.Length
column. - Within each
Species
, keeping the order from the first step above, orderSepal.Length
in 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
.
CodePudding user response:
Here is one way to correct it - i.e. convert to string
and use that string for wherever it needs
df_order <- function(df, group_col, value_col) {
value_col_str <- rlang::as_string(rlang::ensym(value_col))
group_col_str <- rlang::as_string(rlang::ensym(group_col))
df <- df %>%
group_by({{ group_col }}) %>%
mutate("max_{{value_col}}" := max({{value_col}}, na.rm = TRUE)) %>%
as.data.frame() %>%
arrange(desc(!! rlang::sym(glue::glue("max_{value_col_str}")))) %>%
select(-glue::glue("max_{value_col_str}"))
df[,group_col_str] <- factor(df[,group_col_str],
levels = unique(df[,group_col_str]),
ordered = TRUE)
df <- df %>%
arrange({{group_col}}, desc({{value_col}})) %>%
as.data.frame()
return(df)
}
-testing
out <- df_order(iris, Species, Sepal.Length)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 7.9 3.8 6.4 2.0 virginica
2 7.7 3.8 6.7 2.2 virginica
3 7.7 2.6 6.9 2.3 virginica
4 7.7 2.8 6.7 2.0 virginica
5 7.7 3.0 6.1 2.3 virginica
6 7.6 3.0 6.6 2.1 virginica
7 7.4 2.8 6.1 1.9 virginica
8 7.3 2.9 6.3 1.8 virginica
...
identical(out, df)
[1] TRUE