I would like to create a generic function naTrans
that replaces 'NA'
and ''
by NA
.
The problem is that I can't replace the dataframe test
in the global environment by the modified test
dataframe (mydf
) created within the function. Here's my best try.
# Example dataframe containing 'NA'
test <- as.data.frame(matrix(sample(c('NA', 1:9), 10*10, TRUE), 10))
# My function
naTrans <- function (mydf) {
mydf[mydf == 'NA' | mydf ==''] <- NA
assign(deparse(substitute(mydf))[1], mydf, envir = globalenv())
}
test <- naTrans(test)
any(is.na(test))
# [1] FALSE
Surely the problem lies in the last line of code assign(print(deparse(substitute(mydf))), mydf, envir = globalenv())
Any idea?
I hope the comments in the code are clear enough
test <- as.data.frame(matrix(sample(c('NA',1:9),10*10,T),10))
naTrans <- function (mydf) {
mydf[mydf == 'NA' | mydf == ''] <- NA # use and or opertor, %in% don't work on DF but on vectors
return(mydf) # return the modified mydf (the return is optionnal, you may just use mydf here
}
test <- naTrans(test) # replace actual object by caller.