0

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
havij
  • 1,030
  • 14
  • 29
  • 4
    Bad idea. It's not recommended to modify objects across environments. – Rich Scriven Aug 29 '17 at 19:18
  • 5
    Don't write R code like you write C++ code. This will sure lead to hardships later. R is a functional language and functions ideally shouldn't have side-effects (change values outside their scope). Try re-thinking your design in a more functional way. – MrFlick Aug 29 '17 at 19:18
  • There are ways to do that like using `<<-` instead of `<-` but it's bad practice. Look here: https://stackoverflow.com/questions/2628621/how-do-you-use-scoping-assignment-in-r – M-- Aug 29 '17 at 19:20
  • @RichScriven is the way I modify 'a' in above code the correct way to modify an abject? – havij Aug 31 '17 at 15:34
  • @MrFlick what would be a good (and preferably concise) source for learning functional programming in R given I have some decent experience in C++? – havij Aug 31 '17 at 15:34
  • I would just google till you find something you like. I don't have a particular recommendation. – MrFlick Aug 31 '17 at 18:39

1 Answers1

1

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 }

myincas
  • 1,500
  • 10
  • 15