使用动态列名

时间:2018-02-27 18:41:20

标签: r dplyr

我正在尝试根据某个列排列一个tibble(但是根据变量动态设置的名称来设置列)。

下面是我目前正在尝试的代码但是收到错误。第二个代码粘贴工作(我在符号的列名中硬编码,我希望根据变量设置)。

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)

以下是有效的代码,并展示了我要完成的任务:

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 个答案:

答案 0 :(得分:2)

您也可以使用基础R的.flush()

as.symbol

答案 1 :(得分:1)

您需要rlang:symgroup_var从字符symbol转换为符号symbol,然后使用!!将该符号评估为列对象:< / p>

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
# ...