Home > Software engineering >  dplyr::slice_max - Hand over order_by as calculated string
dplyr::slice_max - Hand over order_by as calculated string

Time:11-26

I want to hand over the name of a variable as a string to the order_by argument of dplyr::slice_max(), but I'm getting weird results. Using the iris data here.

library(dplyr)

lastcol <- first(colnames(iris))

My expected result would be a df/tibble of 5 rows, which works while using the actual column name.

i <- iris %>% 
  slice_max(n = 5, order_by = Sepal.Length)

But when handing over the column name, I'm either getting unexpected results or errors.

# unexpected result: one row
i <- iris %>% 
  slice_max(n = 5, order_by = lastcol)

# unexpected result: one row
i <- iris %>% 
  slice_max(n = 5, order_by = !!lastcol)

# Error: `:=` can only be used within a quasiquoted argument
i <- iris %>% 
  slice_max(n = 5, order_by := .data[[lastcol]])

What's missing?

CodePudding user response:

I am not sure what newstrdelcol is. But if you want to use what you have defined in lastcol you can do it with get(lastcol) like this:

library(dplyr)

lastcol <- first(colnames(iris))

iris %>% 
  slice_max(n = 5, order_by = get(lastcol))
#>   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

CodePudding user response:

In the new version, we can also use pick

library(dplyr)
iris %>%
   slice_max(n = 5, order_by = pick(all_of(lastcol)))

-output

   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
  • Related