Omitting NAs just won't work

Hello everybody!

Currently I am trying to generate a new sum variable with mutate(). I want to generate the sums of 10 different variables where row-wise are always different numbers of figures to sum up. So in one row only 2 of 10 variables have summable numbers (The rest is NA), in other rows there 4 or 6, for example.
I already know that in this kind of data frame it's important to omit NAs to sum up rows. That's why I wanted to use na.rm=TRUE, but in mutate() it's just gonna generate a column named "na.rm" with all rows showing the content "TRUE".

Now I have already tried the following approaches:

library(dplyr)
data %>% 
  rowwise() %>% 
  mutate(sum = sum(a,b,c, na.rm=TRUE))
data %>%
  mutate(sum = rowSums(., na.rm = TRUE))

Source: r - ignore NA in dplyr row sum - Stack Overflow

None of these approaches works in my case. The sum variable just remains NA in all rows which contain at least one NA. So I guess the NAs won't be omitted properly for some reason, even though I put na.rm on "TRUE".
I have also seen that the operations in the code blocks above just won't do anything. They won't generate a new sum column or change the existing one from the mutate() operation which won't omit the NAs.

I gotta overlook something and I just don't know what.

The rowSums() approach works fine if you nest the selection inside it.

library(dplyr, warn.conflicts = FALSE)

data <- tibble(a = c(4, NA, 5),
               b = c(NA, NA, 3),
               c = c(9, 2, 4))

data %>% 
  mutate(sum = rowSums(select(., a, b, c), na.rm = TRUE))
#> # A tibble: 3 x 4
#>       a     b     c   sum
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     4    NA     9    13
#> 2    NA    NA     2     2
#> 3     5     3     4    12

Created on 2020-09-14 by the reprex package (v0.3.0)

Now it's getting really weird, siddharthprabhu:

I have copy-pasted your code (which works just fine here) in my code Markdown and it just won't generate a sum column.

What you can see here is the result after I executed the copy-pasted operations. Is there something which blocks this operation...?
02

You haven't assigned the result back to data. So View(data) just gives you the original tibble.

Dear siddharthprabhu,

It just worked out fine. I am just as thankful to you as I am feeling stupid right now.

Best regards

No worries. It happens to the best of us at times. :grinning:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.