gpt4 book ai didi

r - 使用动态列名在 dplyr 中按自定义顺序排列

转载 作者:行者123 更新时间:2023-12-03 23:17:04 25 4
gpt4 key购买 nike

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

以下是我目前正在尝试但出现错误的代码。第二个代码粘贴有效(我在符号的列名中进行了硬编码,我想根据变量进行设置)。

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)

最佳答案

您也可以使用 as.symbol从基础 R

test_tbl_final <- test_tbl %>%
dplyr::arrange(factor(!!as.symbol(group_var), levels = order_var), date)

关于r - 使用动态列名在 dplyr 中按自定义顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com