简体   繁体   中英

R Update Single Vector Element from Function

I am relatively new to R, and have come across a situation that confuses me. 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? 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. Is this because of some scope or mutability thing I haven't read about?

You can use assign to set a value to a variable name in the environment of your choice. In the function below, the default environment is the caller's environment.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM