user13874
user13874

Reputation: 387

r functions: print all arguments as a string.

I am trying to combine all my arguments into a single string. I currently have the below function that works fine when I pass only text. But it breaks down when I include another R function into the argument.

f <- function(x, y, z) {
  paste(substitute(x), substitute(y), substitute(z), sep = ",")
}

>f(hello, world)
[1] "hello,world,"

>f(hello=sum(x), world)
Error in f(hello = sum(x), world) : unused argument (hello = sum(x))

Ideally, I want it to print "hello=sum(x), world,"

Also, is there a way to extend this to an infinite number of arguments?

Thanks in Advance.

Upvotes: 2

Views: 624

Answers (1)

MrFlick
MrFlick

Reputation: 206576

Maybe something like this would work for you in the general calse

f <- function(...) {
  xx<-lapply(sys.call()[-1], deparse)
  paste0(ifelse(nchar(names(xx))>0, paste0(names(xx),"="), ""), unlist(xx), collapse=", ")
}
f(hello=sum(x), world)
# [1] "hello=sum(x), world"

Upvotes: 1

Related Questions