Home > database >  Can a unnamed function be called in R?
Can a unnamed function be called in R?

Time:03-11

Let's assume we have the following R code at the beginning of a R script named script.R:

function(input) { 
 output <- input*input
 return(output)
}

Is there a valid way to call this unnamed function in the reminder of script.R?

CodePudding user response:

This is possible, but it's not advisable. You would have to use eval and parse (or similar) to do it.

thisfile.R

function(input) {
 output <- input*input
 return(output)
}

# This can be many lines later:
fun <- eval(parse(text = paste(readLines("thisfile.R", 4), collapse = "\n")))

# Now you can use the function.
print(sapply(1:5, fun))

And sourcing it gives:

source("thisfile.R")
#> [1]  1  4  9 16 25

Not that although the function is stored as fun in the above example, you could use it directly, e.g.

print(sapply(1:5,
  eval(parse(text = paste(readLines("thisfile.R", 4), collapse = "\n")))))

And of course it would no longer work if you changed the filename or moved it to a different location.

  •  Tags:  
  • r
  • Related