[英]R Update Single Vector Element from Function
I am relatively new to R, and have come across a situation that confuses me.我对 R 比较陌生,遇到了让我感到困惑的情况。 I was updating some values in a vector that I initialized beforehand, and realized that the values were not updating.
我正在更新预先初始化的向量中的一些值,并意识到这些值没有更新。 After spending a couple hours trying to debug, I come here.
在花了几个小时尝试调试后,我来到了这里。
The minimal code can be summarized like this:最小的代码可以总结如下:
incr <- function(v) {
v[1] = v[1] + 1
}
vec = 0
incr(vec)
Why would I make an increment function?为什么我要增加 function? I had a vector meant to store counts for each type of customly defined categories, and would switch on some factors to tell which counter to increment.
我有一个向量用于存储每种类型的自定义类别的计数,并会打开一些因素来判断要增加哪个计数器。 But ultimately this code is the fundamental idea that's at the core of it.
但最终,这段代码是其核心的基本思想。
The behaviour I expect is that vec[1]
's value be changed from 0 to 1. However vec[1]
remains at 0 when looking at it in the debugger.我期望的行为是
vec[1]
的值从 0 更改为 1。但是vec[1]
在调试器中查看时保持为 0。 Is this because of some scope or mutability thing I haven't read about?这是因为一些 scope 或我没有读过的可变性吗?
You can use assign
to set a value to a variable name in the environment of your choice.您可以使用
assign
为您选择的环境中的变量名称设置值。 In the function below, the default environment is the caller's environment.在下面的function中,默认环境是调用者的环境。
incr <- function(x, envir = parent.frame()){
xname <- deparse(substitute(x))
x[1] <- x[1] + 1L
assign(xname, x, envir = envir)
}
a <- 0L
incr(a)
a
#[1] 1
incr(a)
a
#[1] 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.