I have a data.frame that has 100 variables. I want to get the sum of three variables only using mutate
(not summarise
).
If there is NA in any of the 3 variables, I still want to get the sum
. In order to do this using mutate
, I replaced all NA
values with 0
using ifelse
then I got the sum
.
library(dplyr)
df %>% mutate(mod_var1 = ifelse(is.na(var1), 0, var1),
mod_var2 = ifelse(is.na(var2), 0, var2),
mod_var3 = ifelse(is.na(var3), 0, var3),
sum = (mod_var1+mod_var2+mod_var3))
Is there any better (shorter) way to do this?
DATA
df <- read.table(text = c("
var1 var2 var3
4 5 NA
2 NA 3
1 2 4
NA 3 5
3 NA 2
1 1 5"), header =T)
replace(df, is.na(df), 0) %>% mutate(sum = var1 + var2 + var3)
– Queridas