0

Has anyone converted a function in R into a string or text object?

Let's say for a simple square function, I'd want to convert to a text file:

sqfxn <- function(x){
  # Get square of x
  # Expect: 
  # > sqfxn(2)
  # > 4
  output <- x^2
  return(output)
}

Is there a function that will convert sqfxn()to a string object?

fxn_to_text <- function(x){
  # convert function x to text
}

Which will result to:

> txt_fxn <- fxn_to_txt(sqfxn)
> print(txt_fxn)
> "function(x){
  # Get square of x
  # Expect: 
  # > sqfxn(2)
  # > 4
  output <- x^2
  return(output)
  }"

Thanks!

  • See this is actually not exactly a duplicate because user wants to keep comments within function. But don't know how to reopen. – s_baldur Jun 08 '20 at 09:28

3 Answers3

2

Using capture.output():

fun <- paste(capture.output(sqfxn), collapse = "\n")
cat(fun)
# function(x){
#   # Get square of x
#   # Expect: 
#   # > sqfxn(2)
#   # > 4
#   output <- x^2
#   return(output)
# }
s_baldur
  • 29,441
  • 4
  • 36
  • 69
1

I'm rooting for dput:

sqfxn <- function(x){
  # Get square of x
  # Expect: 
  # > sqfxn(2)
  # > 4
  output <- x^2
  return(output)
}

dput(sqfxn)
Linards Kalvans
  • 479
  • 2
  • 8
0

You can use body which as the name suggests returns the body of the function.

body(sqfxn)

#{
#    output <- x^2
#    return(output)
#}

However, this does not capture comments written inside the function.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213