Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply own function using lapply?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

survey1 <- lapply(survey1, replacewithna)

Currently I have the following error: "Error in if (x == -99) { : the condition has length > 1"

>Solution :

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 lapplying the function and keep the dimensions, the tabular format, is

survey1[] <- lapply(survey1, replacewithna)

The square parenthesis are very important.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading