havij
havij

Reputation: 1180

Modifying objects inside a function in r

I am new to R. So basically I have 2 questions:

  1. In C++ we can pass objects as references to be able to return multiple modified objects from a function. What is equivalent way to modify multiple objects inside a function? (for example, a and b in fyfunc)
  2. In below code, I thought since I have access to b inside myfunc, I could modify it. But apparently, it's a copy of b. Is there anyway to actually modify b inside myfunc?
a <- c(1,2,3)
b <- c(4,5,6)

myfunc <- function(a) {
  b <- b+1
  cat(b) # prints: 5 6 7
  a <- a+1
}

a <- myfunc(a)
a
b  # stil 4 5 6

Upvotes: 0

Views: 466

Answers (1)

myincas
myincas

Reputation: 1550

you can use <<- instead of <- or assign('b', b+1, envir = globalenv()) in function myf.

myf <- function(a) { assign('b', b+1, envir = globalenv()) cat(b) # prints: 5 6 7 a <- a+1 }

Upvotes: 1

Related Questions