r - 在 R 中为另一个环境中的对象的一部分赋值

标签 r environment-variables environment assignment-operator

假设我在环境 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))

有没有人有一个优雅的解决方案。

最佳答案

应避免使用

eval(parse())。您可以像这样引用环境:

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
  env[[var_str]][2:3] <- (env[[var_str]][2:3])^2 + rep(env$v,2) + input^3/input

}


f("x", e, 1:2)
e$x
#[1]  1  7 15

关于r - 在 R 中为另一个环境中的对象的一部分赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050094/

相关文章:

visual-studio-2015 - 如何在 Visual Studio 测试中使用 ASP.NET Core 环境变量

php - mysqli_fetch_assoc()期望参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

asp.net - 如果我的 ASP.NET Web 应用程序不适合运行时?

r - 与 as.POSIXct 相比,为什么 lubridate 函数如此慢?

r - 从 R 中的向量中累积选取元素

Python 不加载 _fileio 库

python - 如何从 Python 为当前命令提示符 session 设置环境变量

svn - 改善我们的工作发展环境

r - 获取函数的命名空间

r - R 中多维尺度 (MDS) 的预测值