2

lets say that I have this dataframe in R

df <- read.table(text="
   id      a        b        c
1  42      3        2       NA
2  42     NA        6       NA
3  42      1       NA        7", header=TRUE)

I´d like to calculate all columns to one, so result should look like this.

   id      a        b        c        d
1  42      3        2       NA        5
2  42     NA        6       NA        6
3  42      1       NA        7        8

My code below doesn´t work since there is that NA values. Please note that I have to choose columns that I want to count since in my real dataframe I have some columns that I don´t want count together.

df %>%
  mutate(d = a + b + c)
MrFlick
  • 195,160
  • 17
  • 277
  • 295

1 Answers1

2

You can use rowSums for this which has an na.rm parameter to drop NA values.

df %>% mutate(d=rowSums(tibble(a,b,c), na.rm=TRUE))

or without dplyr using just base R.

df$d <- rowSums(subset(df, select=c(a,b,c)), na.rm=TRUE)
MrFlick
  • 195,160
  • 17
  • 277
  • 295