打印出传递给函数的变量

Print Out Variables Passed Into Functions

我有 python 的背景,但我是 R 的新手(需要尽快学习),遇到一个问题:

我正在开发一个函数来打印出传递到我的函数中的变量,有点简单。

hello_world <- function(fn, num) {
    print("The stuff you sent in were "$fn" and "$num")
} 

所以如果我这样调用 hello world:

hello_world("foo", 3:5)

我应该看看

The stuff you sent in were "foo" and "3:5"

我尝试了 print("$foo", "$num")...仍然有问题。我如何在不使用 sprint 的情况下执行此操作?

使用paste到assemble要打印的字符串。 请注意,由于 3:5 是一个向量,因此第一个 paste 使用参数 collapse.
我还包括了 3 种不同的打印方式。

hello_world <- function(fn, num) {
  num_string <- paste(num, collapse = ",")
  msg <- paste("The stuff you sent in were", dQuote(fn), "and", dQuote(num_string))
  # 3 ways of printing
  print(msg)
  cat(msg, "\n")    # needs the newline character
  message(msg)      # this will default to printing in red
} 
hello_world("foo", 3:5)
#> [1] "The stuff you sent in were “foo” and “3,4,5”"
#> The stuff you sent in were “foo” and “3,4,5”
#> The stuff you sent in were “foo” and “3,4,5”

reprex package (v2.0.1)

创建于 2022-06-03

我们可以使用 deparse/substitute 从 'num' 获取输入,然后使用 paste

创建一个字符串
hello_world <- function(fn, num) {
      num <- deparse(substitute(num))
      cat(paste0("The stuff you sent in were ", '"', fn, '"',
              " and ", '"', num, '"'), "\n")
                    }

-测试

> hello_world("foo", 3:5)
The stuff you sent in were "foo" and "3:5" 

只需使用 cat 而不是 print ,

hello_world <- function(fn, num) {
  cat("The stuff you sent in were \"" , fn , "\" and \"" , num , "\"" , sep = "")
} 

hello_world("foo", 3:5)
#> The stuff you sent in were "foo" and "345"

hello_world("foo", "3:5")
#> The stuff you sent in were "foo" and "3:5"

reprex package (v2.0.1)

创建于 2022-06-03

这是一个您不必指定参数的选项:

library(purrr)

hello_world <- function(fn, num) {
  params <- as.character(match.call()[-1])
  out <- sub(paste(map_chr(params, ~paste("`", ., "`",  " and")), collapse = ' '), pattern = " [[:alpha:]]*$", replacement = "")
  paste0('The stuff you sent in were ', out)
} 

hello_world('foo', 3:5)
#> [1] "The stuff you sent in were ` foo `  and ` 3:5 ` "

因此您可以将其扩展为:

library(purrr)

hello_world <- function(fn, num, apple, banana, cheeseburger) {
  params <- as.character(match.call()[-1])
  out <- sub(paste(map_chr(params, ~paste("`", ., "`",  " and")), collapse = ' '), pattern = " [[:alpha:]]*$", replacement = "")
  paste0('The stuff you sent in were ', out)
} 

hello_world('foo', 3:5, 'yes', 'no', 'definitely')
#> [1] "The stuff you sent in were ` foo `  and ` 3:5 `  and ` yes `  and ` no `  and ` definitely ` "