0

I'm having a strange problem that I can't wrap my head around. I have a function in R that compares two vectors at position x and then inserts the vector into a matrix depending on that condition. Within the function, it replaces the column fine, but if I call the matrix afterward, it returns the original values. I've attached a simplified version of the code below.

## define matrix names and size
r1w <- matrix(c(0), nrow=4, ncol=4)
r1l <- matrix(c(0), nrow=4, ncol=4)
## vectors that should replace column in matrix
b <- c(1, 2, 3, 4)
a <- c(3, 4, 5, 6)

## Function
playgame <- function(x, y, r, g) {
  if (x[r] > y[r]) {
    (r1w[, g] <- x); r1l[, g] <- y; View(r1w)
  } else {
    (r1w[, g] <- y); r1l[, g] <- x
  }
}
## this returns a changed matrix
playgame(a, b, 1, 1)
## calling afterwards returns original matrix
r1w

If anyone could tell me where I made a mistake I would be forever in your debt.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Jack
  • 1
  • 5
    That's how R works. Changes made in a function are local. There are ways to have side effects outside the function, but you should avoid them. To do what you want, have your function return the modified value, and call it as `r1w <- playgame(a,b,1,1)`. – user2554330 Mar 23 '22 at 18:18
  • 1
    I realize that this Q did not ask about "call by reference", but the listed duplicate was found with a search on just words in the question header, and the answers do address how to "change" a variable value properly (one of the peculiarities of R for persons familiar with a different programming style), so I think it's an acceptable "duplicate". – IRTFM Mar 23 '22 at 18:40

0 Answers0