Shgidi
Shgidi

Reputation: 154

mutating global objects in a function in R/passing objects by reference

I have a few dataframes in R, e.g:

df1
df2
df3

and I'd like to cinduct a few action on them, e.g clear NA values from them:

df1[is.na(df1)]=0
df2[is.na(df2)]=0
df3[is.na(df3)]=0

I though I could do something like this:

lapply(c(df1,df2,df3),function(x){x[is.na(x)]=0}) 

but it doesn't seem to work... I've tried using <<- as well.

Am I missing something? How can I change a global object inside a function?

Upvotes: 0

Views: 67

Answers (1)

akrun
akrun

Reputation: 887088

We can use list2env to make the changes done with the lapply to reflect in the global environment (though not recommended as we can do all the operations in the list).

list2env(lapply(mget(paste0('df', 1:3)), function(x) 
      replace(x, is.na(x), 0)), envir=.GlobalEnv)
df1
#  col1 col2
#1    0    1
#2    1    2
#3    2    0
#4    3    4

data

df1 <- data.frame(col1= c(NA, 1:3), col2= c(1:2, NA, 4))
df2 <- data.frame(col1= c(1:3, NA), col2= c(1, NA, 3, 4))
df3 <- data.frame(col1= c(2,4, NA), col2 = c(1, NA, 2))

Upvotes: 1

Related Questions