I have created a custom function to replace values with NA to understand how functions work in R:
replacewithna <- function(x) {
if(x == -99) {
return(NA)
}
else {
return(x)
}
}
I have a dataframe with several columns and values which contain "-99" in certain elements and want to apply the custom function I created to each element. I have been able to do this with a for loop:
for (i in 1:nrow(survey2)) {
for (j in 1:ncol(survey2)) {
survey2[i,j] <- replacewithna2(survey2[i,j], NA)
}
}
However, I can't do the same with a lapply. How can I use my replace function with a function from the apply family like so:
survey1 <- lapply(survey1, replacewithna)
Currently I have the following error: "Error in if (x == -99) { : the condition has length > 1"
CodePudding user response:
Try a vectorized version of your function with ifelse
or, like below, with is.na<-
.
replacewithna <- function(x) {
is.na(x) <- x == -99
x
}
With ifelse
it is a one-liner:
replacewithna <- function(x) ifelse(x == -99, NA, x)
Note
With both functions, if survey1
or survey2
are data.frames, the correct way of lapply
ing the function and keep the dimensions, the tabular format, is
survey1[] <- lapply(survey1, replacewithna)
The square parenthesis are very important.
CodePudding user response:
Here, you can also use sapply
(which returns a vector or a matrix, and might be more appropriate here) with replace
:
sapply(survey2, function(x) replace(x, x == -99, NA))