R:从文件导入foo作为bar

时间:2018-05-30 09:57:32

标签: r

我正在寻找一种结合了以下两个问题的技术:

  

Define all functions in one .R file, call them from another .R file. How, if possible?

     

The R equivalent of Python from x import y as z

换句话说,我想从别人的.r文件中导入特定的功能。用不同的名字。

3 个答案:

答案 0 :(得分:1)

您可以按如下方式使用func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { resourceLoader.delegateQueue?.async { var request: URLRequest? = loadingRequest.request request?.url = self.url // Add header request?.setValue(HeadersForWS.DeviceOS, forHTTPHeaderField: HeadersForWS.DeviceType) request?.setValue(Utility.getUserId(), forHTTPHeaderField:HeadersForWS.UserId ) if let aRequest = request { let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) session.dataTask(with: aRequest as URLRequest) { (data, response, error) in guard let data = data else { try? loadingRequest.finishLoading() return } loadingRequest.dataRequest?.respond(with: data) loadingRequest.finishLoading() }.resume() } } return true }

在test.R脚本中:

source

然后,使用

来源文件
test <- function() message("Hello")

要拨打某人的密码,请使用

someone <- new.env()
source("test.R", someone)

如果可能,请让某人写一个R包。

答案 1 :(得分:1)

我们在新函数中使用source调用local=TRUE,并仅返回所需的函数:

source1 <- function(path,fun){
  source(path, local= TRUE)
  get(fun)
}

from x import y as z将被写入:

z <- source1(x,y) # where y is a string

示例:

# create 'test.R' file in working directory
write("test  <- function(a,b) a + b
      test2 <- function(a,b) a - b",
      "test.R")

new_fun <- source1("test.R","test2")

new_fun
# function(a,b) a - b
# <environment: 0x0000000014873f08>

test
# Error: object 'test' not found

test2
# Error: object 'test2' not found

# clean up
unlink("test.R")

答案 2 :(得分:0)

AFAIK在R中没有这样的机制。

当然可以做到

x.R y <- function() {do_something}

z.R source("x.R") z <- y rm(y)

更好的选择是将x.R放入包中。然后你简单地做z <- x::y

最佳解决方案是将x.Rz.R转换为包,并将@importFrom x y用于包z,而不必担心更改函数的名称。

相关问题