1

Let's say I have a dataframe df and a list obj.

df<- data.frame(x=c(1, 2, 3, 4),
                y=c(1, 2, 3, 4))

obj <- list(data.frame(z=c(0, 0, 0, 0),
                       a=c(0, 0, 0, 0)),
            data.frame(b=c(0, 0, 0, 0)))

I create a function myFun that modifies one column in df and adds it to the list obj. How do I update both x and o in the global environment? In other words, how do I have the function update df and obj?

myFun <- function(x, o) {
  x[1] <- x[,1]*2
  o <- list(o, x[1])
}

myFun(df, obj)
njasi
  • 126
  • 8
Eric Green
  • 7,385
  • 11
  • 56
  • 102
  • 2
    You can take a look [here](http://stackoverflow.com/questions/2679193/how-to-name-variables-on-the-fly-in-r) or similar, but this is usually a very bad idea – David Arenburg Jan 16 '16 at 22:28
  • See http://stackoverflow.com/questions/1826519/function-returning-more-than-one-value/15140507#15140507 – G. Grothendieck Jan 16 '16 at 22:59

1 Answers1

2

There's global assignment (eg <<-),

myFun1 <- function(x, o) {                                                       
  x[1] <- x[,1]*2                                                                
  o <- list(o, x[1])                                                             
  df <<- x                                                                       
  obj <<- o                                                                      
}

Or you could try returning the objects from your function, then using list2env for a multiassignment.

myFun2 <- function(x, o) {                                                       
  x[1] <- x[,1]*2                                                                
  o <- append(o, x[1])                                                           
  list(obj=o, df=x) #setting names here is important for list2env                                                             
}                                                                                

list2env(myFun2(df, obj), environment())                                         

Alternatively, you could pass in the environment. In R, environments are pass-by-reference,

myFun3 <- function(E) {                                                          
  E$df[1] <- E$df[,1]*2                                                          
  E$obj <- append(E$obj, E$df[1])                                                
}                                                                                

myFun3(environment()) 
Neal Fultz
  • 9,282
  • 1
  • 39
  • 60