如何以编程方式指定列参数?

问题描述 投票:0回答:1

对于

qic()
函数,如何指定存储在字符串变量中的输入数据帧的列?

下面我尝试了多种方式来传递“y”参数。 鉴于 qicharts2 基于 ggplot2,我尝试了一些类似于引用 ggplot2 的选项。 全部失败了。

my_fun <- function(y){
  require(qicharts2)

  qic(x        = i, 
      y        = .data[[y]],  # Hoping it works like ggplot2.
      n        = n, 
      data     = nhs_accidents, 
      chart    = 'p',
      title    = 'Proportion of patients seen within 4 hours',
      ylab     = NULL,
      xlab     = 'Week #')
}

my_var <- "r"
my_fun(my_var)

错误:!无法在数据掩码上下文之外对

.data
进行子集化。运行
rlang::last_trace()
查看错误发生的位置。

以下是我尝试定义参数的一些其他方法以及错误。

y = as.symbol(my_var)

stats::complete.cases(y, n) 中的错误:参数的“类型”(符号)无效

y = {{my_var}}

if (y.name == "NULL") y.name <- deparse(substitute(x)) : the condition has length > 1

出错

y = rlang::as_label(my_var)

stats::complete.cases(y, n) 中的错误:并非所有参数都具有相同的长度

r ggplot2
1个回答
0
投票

要在 qicharts2 中以编程方式指定列,您可以使用 dplyr::pull() 按名称从数据框中提取所需的列。以下是调整 my_fun() 函数的方法:

my_fun <- function(y){
  require(qicharts2)
  qic(x        = i, 
      y        = nhs_accidents %>% dplyr::pull(y),  # Pulls the column based on the string
      n        = n, 
      data     = nhs_accidents, 
      chart    = 'p',
      title    = 'Proportion of patients seen within 4 hours',
      ylab     = NULL,
      xlab     = 'Week #')
}

这应该可以解决您遇到的错误。 dplyr::pull() 允许您以编程方式使用字符串名称引用列。

© www.soinside.com 2019 - 2024. All rights reserved.