1

In the answer found here we have an original function.

myfun <- function(x,y) {
  result <- list(x+y,x*y)
  return(result)
}

They replace the second line of the function with result <- list(2 * x, x * y) by running:

body(myfun)[[2]][[3]][[2]] <- substitute(2*x)

What I am looking to do is add a line to the function instead of replacing to get something like:

myfun <- function(x,y) {
  print(x)
  result <- list(x+y,x*y)
  return(result)
}

Is this possible? I have tried a whole raft of substitute, bquote, eval, parse, quote, and expression commands.

See also https://stackoverflow.com/a/2458377/3362993

jay.sf
  • 60,139
  • 8
  • 53
  • 110
jsta
  • 3,216
  • 25
  • 35

1 Answers1

1

You may manipulate the body of your function using body().

myfun <- function(x,y) {
  result <- list(x+y,x*y)
  return(result)
}
myfun
# function(x,y) {
#   result <- list(x+y,x*y)
#   return(result)
# }

b <- body(myfun)  ## for covenience
b
as.list(b)
# [[1]]
# `{`
# 
# [[2]]
# result <- list(x + y, x * y)
# 
# [[3]]
# return(result)

The body can be handled similar to a list. The print(x) line can be concatenated as an expression to the original elements. Put it back as.call to the body.

body(myfun) <- as.call(c(b[[1]], expression(print(x)), b[[2]], b[[3]]))
myfun
# function (x, y) 
# {
#   print(x)  ## voilĂ !
#   result <- list(x + y, x * y)
#   return(result)
# }

Test:

myfun(1, 2)
# [1] 1
# [[1]]
# [1] 3
# 
# [[2]]
# [1] 2
jay.sf
  • 60,139
  • 8
  • 53
  • 110