Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save function argument as character

I want to save the argument of a function as a variable in r. I've tried deparse, but on a dataframe it returns the wrong thing. Below is what I want.

dataframe <- data.frame(a=c(1, 2, 3), b=c(3, 6, 8))

afunction <- function(arg1, arg2) {
  arg1_character <- deparse(arg1)
  arg2_character <- deparse(arg2)
}

afunction(a ~ b, dataframe)

Based on this simple example I'd want the following output:

arg1_character <- "a~b"
arg2_character <- "dataframe"
like image 928
OLGJ Avatar asked Dec 21 '25 10:12

OLGJ


1 Answers

Try deparse(substitute()).

afunction <- function(arg1, arg2) {
  arg1_character <- deparse(substitute(arg1))
  arg2_character <- deparse(substitute(arg2))
  c(arg1_character, arg2_character)
}

afunction(a ~ b, dataframe)
# [1] "a ~ b"     "dataframe"

Or try match.call()

afunction2 <- function(arg1, arg2) {
  cat('Call:\n')
  match.call()
}
afunction2(a ~ b, dataframe)
# Call:
# afunction2(arg1 = a ~ b, arg2 = dataframe)
like image 195
jay.sf Avatar answered Dec 22 '25 22:12

jay.sf