GNicoletti
GNicoletti

Reputation: 204

Conditional column sort

I have to sort one column in my df by checking a condition on a string.

Basically, I want to look into test.name and based on I want the column to be arranged asc or desc based on the value contained in it.

In the example below, I tried with paste0 after the pipe, but something is not working.

test.name <- "abc"
test.value <- data.frame(a = rnorm(100, 0, 1)
                         , b = rnorm(100, 0, 1))
result <- case_when(test.name == "bcd" ~ "desc"
                    , TRUE ~ "asc")

paste0("arrange(",result,"(b))",sep="")

test.value %>% paste0("arrange(",result,"(b))",sep="")

Upvotes: 1

Views: 57

Answers (1)

akrun
akrun

Reputation: 886938

We could use parse_expr from rlang and evaluate (!!)

library(dplyr)
test.value %>% 
  arrange(!! rlang::parse_expr(case_when(test.name == 'bcd'~
      'desc(b)', TRUE ~ 'b')))

Or we can use across as well

test.value %>%
   arrange(across(b, ~ case_when(test.name == 'bcd' ~ desc(.), TRUE ~.)))

Upvotes: 2

Related Questions