vendredi 31 mars 2017

Write a function in R containing an if/else statement and rowSums(), defining how to handle NAs

I've been searching for answers and trying all I can think of, but nothing works:

I want to write a function to add the values across rows in a dataframe. It's easiest to write a function since I have so many columns and don't always have to add the same ones. Here an example of a dataframe:

ExampleData <- data.frame(Participant = 1:7,
                   Var1 = c(2, NA, 13, 15, 0, 2, NA),
                   Var2 = c(NA, NA, 1, 0, NA, 4, 2),
                   Var3 = c(6, NA, 1, 0, 1, 5, 3),
                   Var4 = c(12, NA, NA, 4, 10, 1, 4),
                   Var5 = c(10, NA, 3, 5, NA, 4, 4))

The conditions: If all values across a row are NA, the sum should be NA. If there is at least one value across a row that is a number (>= 0, or not NA), then rowSums should ignore NA's and add the values.

The best solution I've reached so far is:

addition <- function(x) {
  if(all(is.na(x))){
       NA
  }else{
       rowSums(x, na.rm = TRUE)
  }
}
addition(ExampleData[, c("Var1", "Var2", "Var3")])

The output is: [1] 8 0 15 15 1 11 5

But it should be: [1] 8 NA 15 15 1 11 5

Does anyone know how to do this? Thank you.

Aucun commentaire:

Enregistrer un commentaire