[英]Using name of vector argument in function
我正在編寫一個 function,它傳入一個值向量,我想在 function 中使用這些值進行計算。但是,我還想使用我傳遞的向量的名稱來返回有意義的錯誤消息,但無法確定知道怎么做。
我的 function 看起來像這樣
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))
}
我的 function 電話是這樣的
colours <- c("red","green","blue")
func(colours, 2)
回報
“向量的長度大於2”,但我想說“顏色的長度大於2”
我可以通過添加另一個參數將矢量名稱作為字符串傳遞到 function 中來實現這一點,但我想知道是否有更好的設計方法。
我添加了deparse(substitute(vector))
以將 object 的名稱作為字符串獲取。
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(colours, 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)
Output:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.