【发布时间】:2016-03-07 03:04:47
【问题描述】:
假设我在环境 e 中定义了两个相似的大对象 x、y(数据表)。 我想使用函数 f 以类似的方式更改 x 或 y 的很大一部分,而无需在 f 的执行环境中创建 x 或 y 的副本。示例:
e <- new.env()
e$x <- c(1,2,3) # imagine this to be BIG (ie. dataframe with 200k vars each 500k rows)
e$y <- c(4,5,6) # same here
e$v <- 2 # minor variables
f <- function(var_str, env, input){
# do some computation on parts of var_str which is either "x" or "y"
# and store these right back into e$x or e$y, respectively.
# ie
str <- paste0(var_str,"[2:3] <- (",var_str,"[2:3])^2 + rep(v,2) + ", deparse(input1),"^3/c(100,101)")
eval(parse(text=str), envir= e)
# this does work but I can image there is an easier/more elegant way
# of doing this.
}
我想在全局环境中定义函数并将这个函数应用到 e$x 和 e$y 输入不同的变量。 IE。执行
f("x", e, c(1,2))
f("y", e, c(3,4))
有没有人对此有一个优雅的解决方案。
【问题讨论】:
-
也许你可以使用 R6 类得到你想要的东西:cran.r-project.org/web/packages/R6/vignettes/Introduction.html
标签: r environment-variables environment assignment-operator