在包装函数中从github获取R脚本以供全局会话使用? [英] Sourcing an R script from github, for global session use, from within a wrapper function?

查看:87
本文介绍了在包装函数中从github获取R脚本以供全局会话使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #载入一个在github上持有的R脚本(使用'raw'文本链接)包
require(RCurl)

#check 1
ls()
#character(0)

#从网站读脚本行
u< - https://raw.github.com/tonybreyal/Blog-Reference-Functions/master/R/bingSearchXScraper/bingSearchXScraper.R
script< - getURL(u,ssl。 verifypeer = FALSE)
eval(parse(text = script))

#clean-up
rm(script,u)

#check 2
ls()
#[1]bingSearchXScraper

然而,我真正想做的是将它包装在一个函数中。这就是我遇到问题的地方,我怀疑它与脚本的功能有关,这些脚本的功能只存在于它所调用的函数中。例如,下面是我想要实现的功能:

  source_github<  -  function(u){
#加载包
要求(RCurl)

#从网站读取脚本行并评估
脚本< - getURL(u,ssl.verifypeer = FALSE)
eval(parse(text = script))
}

source_github(https://raw.github.com/tonybreyal/Blog-Reference-Functions/master/R/bingSearchXScraper/bingSearchXScraper.R)

非常感谢您的宝贵时间。

解决方案

/ p>

  eval(parse(text = script),envir = .GlobalEnv)

将结果粘贴到您的默认搜索空间中。当然,用相同的名称覆盖别的东西。

I can source an R script held on github (using the 'raw' text link) as follows:

# load package
require(RCurl)

# check 1
ls()
#character(0)

# read script lines from website
u <- "https://raw.github.com/tonybreyal/Blog-Reference-Functions/master/R/bingSearchXScraper/bingSearchXScraper.R"
script <- getURL(u, ssl.verifypeer = FALSE)
eval(parse(text = script))

# clean-up
rm("script", "u")

# check 2
ls()
#[1] "bingSearchXScraper"

However, what I would really like to do is wrap that up in a function. This is where I run into problems and I suspect it has something to do with the functions of the script only existing locally within the function it's called in. For example, here is the sort of thing I am aiming for:

source_github <- function(u) {
  # load package
  require(RCurl)

  # read script lines from website and evaluate
  script <- getURL(u, ssl.verifypeer = FALSE)
  eval(parse(text = script))
}  

source_github("https://raw.github.com/tonybreyal/Blog-Reference-Functions/master/R/bingSearchXScraper/bingSearchXScraper.R")

Many thanks in advance for your time.

解决方案

Use:

 eval(parse(text = script),envir=.GlobalEnv)

to stick the results into your default search space. Overwriting anything else with the same names, of course.

这篇关于在包装函数中从github获取R脚本以供全局会话使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆