I have a, b, c 3 numbers and a is na (is.na(a)==TRUE).

I want to total these, and the sum is 3, but not na. How to do this? Thank s in advance!

```
a <- NULL
b <- 2
c <- 1
d <- a+b+c
```

I have a, b, c 3 numbers and a is na (is.na(a)==TRUE).

I want to total these, and the sum is 3, but not na. How to do this? Thank s in advance!

```
a <- NULL
b <- 2
c <- 1
d <- a+b+c
```

`d <- sum(a,b,c,na.rm=TRUE)`

1 Like

Utilise the `sum()`

function and specify `na.rm = TRUE`

:

```
a <- NULL
b <- 2
c <- 1
d <- sum(c(a, b, c), na.rm = TRUE)
d
#> [1] 3
```

^{Created on 2021-12-06 by the reprex package (v2.0.1)}

The sum() seems work fine for integer, but somehow doesn't work for this dataset in RStudio on my machine.

Here is the data. After ran codes below, The total is 111.6443 for all rows and avg is 37.21476 for all rows. Do you see the same? What library sum () stays? What was wrong?

```
library(tidyverse)
library(dplyr)
library(tidyr)
test <- data.frame(
stringsAsFactors = FALSE,
PROVNUM = c("15009", "15009", "15010", "15010", "15012"),
SCORE18 = c(NA, 0.735293, 33.027526, 3.382664, 0),
SCORE19 = c(7.344632, 3.030305, NA, 1.106195, 3.252032),
SCORE20 = c(10.778443, NA, 43.902439, 0, 5.084747)
)
df1 <- test%>% mutate(total=sum(c(SCORE18,SCORE19,SCORE20),na.rm=TRUE))
df2 <- df1 %>% mutate(avg=total/3)
```

sums apply over the whole column, so you need to do it by row:

```
df1 <- test %>%
rowwise() %>%
mutate(total = sum(c(SCORE18, SCORE19, SCORE20), na.rm=TRUE)) %>%
ungroup()
```

Perfect! It works.... thank you.

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.