'Can a unnamed function be called in R?
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
