是否有一种方法可以source()
将R中的脚本附加为全局环境(.GlobalEnv
)的父级?
目前,当我获取脚本时,该脚本的所有变量和函数都出现在我的全局(交互)环境中.我想在搜索路径中包含这些变量和函数,但不包括在内.GlobalEnv
.也就是说,我希望源脚本的行为类似于附加的包,它附加在全局环境和基础环境之间(参见高级R 环境中的图)
我有以下Rmd
文件test.Rmd
:
---
title: "test"
output: html_document
---
```{r}
print(y)
```
```{r}
x <- "don't you ignore me!"
print(x)
```
Run Code Online (Sandbox Code Playgroud)
我想以下面的方式调用render:
render('test.Rmd', output_format = "html_document",
output_file = 'test.html',
envir = list(y="hello"))
Run Code Online (Sandbox Code Playgroud)
但它失败了:
processing file: test.Rmd
|................ | 25%
ordinary text without R code
|................................ | 50%
label: unnamed-chunk-1
|................................................. | 75%
ordinary text without R code
|.................................................................| 100%
label: unnamed-chunk-2
Quitting from lines 11-13 (test.Rmd)
Error in print(x) : object 'x' not found
Run Code Online (Sandbox Code Playgroud)
第一块块很好,所以有些东西有效.如果我y
在我的全局环境中定义我可以在没有envir …
假设我有一个闭包add_y(y)
,它返回一个添加到其输入的函数y
。
add_y <- function(y) {
function(x) {
x + y
}
}
add_4 <- add_y(4)
Run Code Online (Sandbox Code Playgroud)
因此 的值add_4
是一个将其输入加 4 的函数。这有效。我想用来展示asdput
的定义add_4
function(x) {
x + 4
}
Run Code Online (Sandbox Code Playgroud)
但这不是 dput 返回的内容。
add_y <- function(y) {
function(x) {
x + y
}
}
add_4 <- add_y(4)
dput(add_4)
#> function (x)
#> {
#> x + y
#> }
Run Code Online (Sandbox Code Playgroud)
有没有办法获取可以在封闭环境之外运行的源代码?
是否可以锁定全局环境并且仍然允许.Random.seed
设置或删除全局环境?在lockEnvironment()
我的用例中,的默认行为过于激进。
lockEnvironment(globalenv())
rnorm(10)
#> Error in rnorm(10) : cannot add bindings to a locked environment
rm(.Random.seed)
#> Error in rm(.Random.seed) :
#> cannot remove bindings from a locked environment
Run Code Online (Sandbox Code Playgroud)
drake
7.0.0版将具有新的保护措施,以保护可重复性。
plan <- drake_plan(
x = {
data(mtcars)
mtcars$mpg
},
y = mean(x)
)
plan
#> # A tibble: 2 x 2
#> target command
#> <chr> <expr>
#> 1 x { data(mtcars) mtcars$mpg }
#> 2 y mean(x)
make(plan)
#> target x
#> fail …
Run Code Online (Sandbox Code Playgroud) 我有一个使用 R 3.6 的项目,我已将 R 升级到 4.0.2,并且想在该项目中使用 4.0.2。我想知道如何去做,或者我应该完全删除renv/
并重建?
我做了以下事情:
> renv::init()
This project already has a lockfile. What would you like to do?
1: Restore the project from the lockfile.
2: Discard the lockfile and re-initialize the project.
3: Activate the project without snapshotting or installing any packages.
4: Abort project initialization.
Run Code Online (Sandbox Code Playgroud)
而且2
从上面的选择来看,这似乎也是合理的。
在以下两种情况下使用一种比另一种有什么优点/缺点?Case-I 将其输出作为环境返回,Case-II 将其输出作为列表返回。
案例一:
function(x) {
ret <- new.env()
ret$x <- x
ret$y <- x^2
return(ret)
}
Run Code Online (Sandbox Code Playgroud)
案例二:
function(x) {
ret <- list()
ret$x <- x
ret$y <- x^2
return(ret)
}
Run Code Online (Sandbox Code Playgroud) r ×6
closures ×1
comparison ×1
knitr ×1
performance ×1
r-markdown ×1
renv ×1
ropensci ×1
version ×1
virtualenv ×1