【问题标题】:Unable to pass non-string arguments in a function [duplicate]无法在函数中传递非字符串参数[重复]
【发布时间】:2021-04-27 22:45:20
【问题描述】:

我正在尝试创建一个函数,它可以传递两个参数来组成一个新的串联字符串。

我希望这个功能

fun1(apple, orange)

生产:

apple and orange

但是,由于某种原因,当我运行此函数时,它无法找到并传递参数。

fun1 <- function(first, second){
  first_str <- as.character(first)
  second_str <- as.character(second) 
  sentence <- str_c(orig_str ," and ", dest_str)
  return(sentence)

Error in fun1(apple, orange) : object 'apple' not found

如果我立即传递一个字符串,这将起作用,

fun1("apple", "orange")
[1] apple and orange

我的目的是让用户填写输入栏上的参数,并让函数将其转换为字符。因此,我不想要求用户使用 "" 并以字符串格式传递参数。有什么好的选择?

【问题讨论】:

  • 一般来说最好不要设计你的函数来接受未计算的对象fun1 &lt;- function(first, second) paste(first, "and", second)是你所需要的,如果字符串被传递然后用户也可以轻松地传递变量:fun1("first", "second")或v1 &lt;- "first"; v2 &lt;- "second"; fun1(v1, v2)
  • 究竟什么是“输入栏”?请注意,通过这样的设置,您将只能接受可以解释为符号的单词。您将永远无法输入包含空格或连字符或其他任何内容的单词。

标签: r string function arguments


【解决方案1】:

这行得通,但我怀疑其他人会给出一个更有说服力的答案:

fun1 <- function(first, second){
  first <- enquo(first)
  second <- enquo(second)
  first <- as.character(first)[2]
  second <- as.character(second)[2]
  sentence <- str_c(first ," and ", second)
  return(sentence)
}
fun1(apple, orange)
# [1] "apple and orange"

【讨论】:

    【解决方案2】:

    Dave 的解决方案适用于一定数量的参数。

    另一种更笨拙的选择是在您的函数中使用省略号 (...),然后获取所提供参数的名称。

    我不推荐此解决方案,因为如果有任何具有所提供名称的全局变量,它将不起作用。

    如果您决定提供字符串作为输入,下面是一个可行的示例。

    fun1 <- function(...) {
    args <- list(...)
    lappy(args, paste)
    }
    

    【讨论】:

    【解决方案3】:

    请注意,readline(prompt= "some prompt") 函数从终端收集用户内容作为字符。因此,如果您需要 2 个输入,您可以将它们收集在 2 个由函数包装的 readline 提示中:

    fun1 <- function(){
      str1 <- readline(prompt="Enter string 1: ")
      str2 <- readline(prompt="Enter string 2: ")
      strs <- paste(str1, "and", str2, sep = " ")
      return(strs)
      
    }
    

    【讨论】:

      【解决方案4】:

      您可能正在寻找deparse(substitute))。

      fun2 <- function(first, second) {
        paste0(deparse(substitute(first)), " and ", deparse(substitute(second)))
      }
      fun2(apple, orange)
      # [1] "apple and orange"
      

      【讨论】:

      • 这很好用,但出于某种原因,它会自动在“and”和输入字符串之间添加空格,这使得它相当不灵活。
      • @JoshuaBudi 改用paste0 并在需要时将空格放入绑定字符串(编辑)。
      猜你喜欢
      • 2015-03-30
      • 2012-03-27
      • 2015-11-04
      • 2018-10-29
      • 1970-01-01
      • 2018-06-26
      • 2021-09-22
      • 2014-01-21
      • 2017-02-19
      相关资源
      最近更新 更多