r - 确定传递给函数的值是否是一个变量

标签 r function stringr

简短版本:函数如何区分接收这两个输入?

value <- "asdf"
"asdf"

一个可重现的例子: 假设我有一个寻找邪恶的函数,或者至少寻找字符串 "evil"

library(stringr)

Find_Evil <- function(x) {
  x <- str_to_lower(x)
  if(str_detect(x, "evil")) {
    message("Evil detected")
  } else {
    return(x)
  }
}

该函数可以很好地检测其输入中是否存在 "evil"

Find_Evil("this has some evil in it")
Evil detected

如果我还想检测变量名中是否包含 evil 怎么办?这在不应该通过的时候通过了。

sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
[1] "sounds good but isn't"

我可以使用 deparse(substitute()) 检查变量名,但我如何首先检查某物是否为变量?我想要的是符合以下元代码的内容(不起作用):

Find_Evil <- function(x) {
  x <- str_to_lower(x)
  if (x is a variable) { # this is the part I need help on
    x_name <- str_to_lower(deparse(substitute(sneaky_evil))) # convert value name to string
    evil_name <- str_detect(x_name, "evil") # check name for evil
    evil_x <- str_detect(x, "evil") # check contents for evil
    if (sum(evil_name, evil_x) != 2) { # if either name or contents contains evil
      message("evil detected")
    } else {
      return(x)
    }
  } else {
    if (str_detect(x, "evil")) { # if x isn't a variable just check x (no name)
      message("Evil detected")
    } else {
      return(x)
    }
  }

最佳答案

可能,这样的事情会有所帮助:

Find_Evil <- function(x) {
   var_type <- substitute(x)
   var_name <- deparse(substitute(x))
   if(grepl('evil', var_name) & is.name(var_type)) {
     return("evil detected in variable")
   }
   x <- tolower(x)
   if(grepl('evil', x)) {
     return("Evil detected in string")
   }
   else return(x)
}

sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
#[1] "evil detected in variable"

sneaky_only <- "sounds good but isn't"
Find_Evil(sneaky_only)
#[1] "sounds good but isn't"

sneaky_only <- "sounds good but evil"
Find_Evil(sneaky_only)
#[1] "Evil detected in string"

Find_Evil("sounds good but isn't")
#[1] "sounds good but isn't"

Find_Evil("sounds good but evil")
#[1] "Evil detected in string"

关于r - 确定传递给函数的值是否是一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61158880/

相关文章:

r - R 中的数据帧行必须是唯一的?

c - 传递指针数组并接收错误消息

html - 如何合并重复函数的 Jquery 选择器?

javascript - node.js 由服务器响应中的异步函数调用产生

r - 获取提取的单词的上下文

r - java.io.IOException:没有用于方案的文件系统:R编程中的hdfs

r - 让 transition_states、geom_label_repel 和 enter_fade 协同工作

r - 如何用 R 找到回归线上的最低值和最高值?

R:如何删除包含特定字符模式的字符串?