7

I am trying to arrange a tibble based on a certain column (but setting the column based on a name dynamically set by a variable).

Below is the code I currently am trying but am getting an error. The second paste of code works (where I have hard coded in the column name of symbol which I want to be set based off of a variable instead).

library(tidyverse)

group_var <- "symbol"

date_seq <- seq(as.Date("2000-01-01"), as.Date("2009-12-31"), by = "days")
test_tbl <- tibble::tibble("date" = rep(date_seq, 3),
                           "symbol" = rep(c("test3", "test1", "test2"), each = length(date_seq)),
                           "value" = c(rnorm(length(date_seq), sd = 0.05),
                                       rnorm(length(date_seq), sd = 0.05),
                                       rnorm(length(date_seq), sd = 0.05)))

order_var <- c("test1", "test2", "test3")
test_tbl_final <- test_tbl %>%
  dplyr::arrange(factor(!!group_var, levels = order_var), date)

Below is the code that works and shows what I am trying to accomplish:

library(tidyverse)

date_seq <- seq(as.Date("2000-01-01"), as.Date("2009-12-31"), by = "days")
test_tbl <- tibble::tibble("date" = rep(date_seq, 3),
                           "symbol" = rep(c("test3", "test1", "test2"), each = length(date_seq)),
                           "value" = c(rnorm(length(date_seq), sd = 0.05),
                                       rnorm(length(date_seq), sd = 0.05),
                                       rnorm(length(date_seq), sd = 0.05)))

order_var <- c("test1", "test2", "test3")
test_tbl_final <- test_tbl %>%
  dplyr::arrange(factor(symbol, levels = order_var), date)

2 Answers 2

7

You can also use as.symbol from base R

test_tbl_final <- test_tbl %>%
  dplyr::arrange(factor(!!as.symbol(group_var), levels = order_var), date)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, love the base R function mention.
3

You need rlang:sym to convert group_var from character symbol to a symbol symbol and then use !! to evaluate the symbol as a column object:

test_tbl %>% 
    arrange(factor(!!rlang::sym(group_var), levels = order_var), date)

# A tibble: 10,959 x 3
#         date symbol         value
#       <date>  <chr>         <dbl>
# 1 2000-01-01  test1  0.0519143671
# 2 2000-01-02  test1 -0.0464782439
# 3 2000-01-03  test1 -0.0295441613
# ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.