I want to set the NA values to zero for a specific column. I followed the instructions from this question, and the solution works at the R prompt.
However, it does not work when I place the commands in a function.
Here is an example:
d <- data.frame(colA=c("Joe", "Jane", "Jack"), colB=c(25, NA, 35), colC=c(100, 200, NA))
d
# colA colB colC
# 1 Joe 25 100
# 2 Jane NA 200
# 3 Jack 35 NA
I want to remove the NA in colB, so I followed another StackOverflow post to produce this working command: d$colB[is.na(d$colB)] <- 0
But now I want to write a function so that I don't have to type the column name twice, so the column is passed as an argument.
setNAToValue <- function(column, value) {
column[is.na(column)] <- value
}
However, when I apply it, nothing happens:
setNAToValue(d$colB, 0)
d
# colA colB colC
# 1 Joe 25 100
# 2 Jane NA 200
# 3 Jack 35 NA
Now, when I change the <-
to <<-
(following the instructions in this post), I get an error:
setNAToValue(d$colB, 0)
# Error in column[is.na(column)] <<- value : object 'column' not found
How can I fix the problem?