让我们假设在一个名为script.R的R脚本开头有以下R代码:
function(input) {
output <- input*input
return(output)
}在script.R提醒中,是否有有效的方法调用这个未命名的函数?
发布于 2022-03-11 09:23:54
这是可能的,但不可取。您必须使用eval和parse (或类似的)来完成它。
thisfile.R file.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))它所提供的资源:
source("thisfile.R")
#> [1] 1 4 9 16 25并不是说在上面的例子中函数被存储为fun,但是您可以直接使用它。
print(sapply(1:5,
eval(parse(text = paste(readLines("thisfile.R", 4), collapse = "\n")))))当然,如果您更改文件名或将其移到不同的位置,它将不再工作。
https://stackoverflow.com/questions/71434347
复制相似问题