I come from a python background but I'm new to R (need to learn it in a hurry), stuck at an issue:
I am developing a function to print out the variables passed into my function, kinda simple.
hello_world <- function(fn, num) {
print("The stuff you sent in were "$fn" and "$num")
}
so if I call hello world as such:
hello_world("foo", 3:5)
I should see
The stuff you sent in were "foo" and "3:5"
I tried print("$foo", "$num")...still having issues. How can I do this without using sprint?
CodePudding user response:
We could use deparse/substitute
to get the input as it is from 'num', and then create a single string with paste
hello_world <- function(fn, num) {
num <- deparse(substitute(num))
cat(paste0("The stuff you sent in were ", '"', fn, '"',
" and ", '"', num, '"'), "\n")
}
-testing
> hello_world("foo", 3:5)
The stuff you sent in were "foo" and "3:5"
CodePudding user response:
Use paste
to assemble the string to be printed.
And note that since 3:5
is a vector, the first paste
uses argument collapse
.
I have also included 3 different ways of printing.
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”
Created on 2022-06-03 by the reprex package (v2.0.1)
CodePudding user response:
Just use cat
instead of 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"
Created on 2022-06-03 by the reprex package (v2.0.1)
CodePudding user response:
Here's an option where you don't have to specify your parameters:
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 ` "
So you could extend this to something like:
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 ` "