【问题标题】:Using name of vector argument in function在函数中使用向量参数的名称
【发布时间】:2021-09-27 10:27:28
【问题描述】:

我正在编写一个传入值向量的函数,并且我想在函数内使用这些值进行计算。但是,我也想使用我传递的向量的名称来返回有意义的错误消息,但不知道该怎么做。

我的函数是这样的

func <- function(vector, minimumvalue){
    if(length(vector)==1){
      return(1)}
    else if (length(vector)<minimumvalue){
      stop(paste0("The length of vector is less than ",minimumvalue))}
    else if (length(vector)>minimumvalue){
      stop(paste0("The length of vector is more than ",minimumvalue))}
    else (return(vector))
}

我的函数调用如下所示

colours <- c("red","green","blue")
func(colours, 2)

一个返回

“向量的长度大于2”,但我想说“The 颜色长度大于 2"

我可以通过添加另一个参数来实现这一点,该参数将向量的名称作为字符串传递给函数,但我想知道是否有更好的设计方法。

【问题讨论】:

    标签: r


    【解决方案1】:

    我添加了deparse(substitute(vector)) 以将对象的名称作为字符串获取。

    func <- function(vector, minimumvalue){
      if(length(vector)==1){
        return(1)}
      else if (length(vector)<minimumvalue){
        stop(paste0("The length of ",deparse(substitute(vector))," is less than ",minimumvalue))}
      else if (length(vector)>minimumvalue){
        stop(paste0("The length of ",deparse(substitute(vector))," is more than ",minimumvalue))}
      else (return(vector))
    }
    
    colours <- c("red","green","blue")
    
    func(colours, 2)
    

    func(colors, 2) 出错:颜色的长度超过 2

    【讨论】:

      【解决方案2】:

      使用glue 库,您可以更轻松地格式化字符串:

      library(glue)
      func <- function(vector, minimumvalue){
          if(length(vector)==1){
            return(1)}
          else if (length(vector)<minimumvalue){
            stop(paste0(glue("The length of vector is less than "),minimumvalue))}
          else if (length(vector)>minimumvalue){
            stop(paste0(glue("The length of {substitute(vector)} is more than "),minimumvalue))}
          else (return(vector))
      }
      
      colours <- c("red","green","blue")
      func(colours, 2)
      

      输出:

      Error in func(colours, 2) : 
      The length of colours is more than 2
      

      或者甚至更好地使用glue 模块来格式化minimumvalue

      library(glue)
      func <- function(vector, minimumvalue){
          if(length(vector)==1){
            return(1)}
          else if (length(vector)<minimumvalue){
            stop(glue("The length of {substitute(vector)} is less than {minimumvalue}"))}
          else if (length(vector)>minimumvalue){
            stop(glue("The length of {substitute(vector)} is more than {minimumvalue}"))}
          else (return(vector))
      }
      
      colours <- c("red","green","blue")
      func(colours, 2)
      

      你甚至不需要paste0

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多