johnny
johnny

Reputation: 631

Quoting an argument passed to a function

Suppose I have the following function:

print_argument <- function(vector) {
  message(substitute(vector))
}

This function does what I want for the most part, e.g.,

abc <- 1:3
print_argument(abc)

# output:
# abc

But it doesn't work for the following argument:

df <- data.frame(a = 1:3)
col_name <- "a"
print_argument(df[[col_name]])

# output:
# [[dfcol_name

How would you update the function so that it also prints (using the message function) arguments like df[[col_name]] verbatim?

That is, how would you make it print (using the message function) the following: df[[col_name]]

Upvotes: 2

Views: 38

Answers (1)

akrun
akrun

Reputation: 886938

We can deparse before wrapping with message

print_argument <- function(vector) {
  message(deparse(substitute(vector)))
 }

print_argument(df[[col_name]])
#df[[col_name]]

print_argument(abc)
#abc

When we get the substitute output, it is not a single string, and its components can be checked with as.list

print_argument <- function(vector) {
    as.list(substitute(vector))
   }
print_argument(df[[col_name]])
#[[1]]
#`[[`

#[[2]]
#df

#[[3]]
#col_name


print_argument(abc)
#[[1]]
#abc

Upvotes: 1

Related Questions