Oscar Kjell
Oscar Kjell

Reputation: 1651

In R save input names within function as a comment

I would like to save the inputs/commands within a function as a comment in the end of the function. Please see example below.

Name1 <- c(1, 2, 3)
Name2 <- c(4, 5, 6)

addition <- function(x, y){
  z <- x + y
  comment(z) <- paste(x, y)
  z
}
z <- addition(x=Name1, y=Name2)
comment(z)

I would like the output of comment(z) to be Name1 Name2.

Upvotes: 1

Views: 57

Answers (1)

Roland
Roland

Reputation: 132706

Store the comment as a "comment" attribute.

R already has the following functions for "comment" attributes but you could define them yourself, e.g., if you want to name the attribute differently. The advantage of the inbuilt "comment" attribute is that print doesn't print it. The disadvantage is that its content is restricted to text.

##assignment function
#"comment<-" <- function(x, value) {
#  attr(x, "comment") <- value
#  x
#}
#
##accessor function    
#comment <- function(x) attr(x, "comment")

You then need to substitute the arguments into paste:

addition <- function(x, y){
  z <- x + y
  comment(z) <- paste(substitute(x), substitute(y))
  z
}
z <- addition(x=Name1, y=Name2)
comment(z)
#[1] "Name1 Name2"

Personally, I'd prefer comment(z) <- deparse(match.call()).

Upvotes: 2

Related Questions