R错误:从文件加载时找不到功能

时间:2015-04-03 14:49:25

标签: r

这对我来说有点难以描述,但请参阅下面的示例。我试图通过将脚本加载到函数中来隔离一些R脚本的范围。但是,在加载嵌套式设备时,这并不起作用。功能。在下面的例子中,函数' inside'可以在加载后调用,但随后函数“在外面”#39;错误说它无法找到内部功能。'

#this would be in some file
inside <- function(a, b){
  return(a+b)
}    

outside <- function(c, d){
  inside(c, d)
}    

save.image("my_r_functions.model")    

rm(list = ls())    

#this would be in some other file
wrapper <- function(d, e){
  load("my_r_functions.model")
  print(paste('inside works: ', inside(d,e)))
  print('but outside can not find inside')
  outside(d,e)
}    

wrapper(1,2)

输出:

[1] "inside works:  3"
[1] "but outside can not find inside"
Error in outside(d, e) : could not find function "inside"

1 个答案:

答案 0 :(得分:2)

您没有指定要加载的位置。只需将envir=globalenv()(或envir=environment(wrapper))添加到要加载的调用中。

 wrapper <- function(d, e){
     load("my_r_functions.model",envir=environment(wrapper))
     print(paste('inside works: ', inside(d,e) ))
     print('but outside can not find inside')
     outside(d,e)
 }    

wrapper(1,2)

将起作用