Is there a quick way to run multiple arithmetic operations across data frame variables while ignoring cases with NAs? I've put a simple example below.
It seems I could add intermediary variables or 'if' statements but that seems too convoluted.
d1<-c(2,2,2,2)
d2<-c(1,1,1,1)
d3<-c(1,1,NA,NA)
df<-data.frame(d1,d2,d3)
df
d1 d2 d3
1 2 1 1
2 2 1 1
3 2 1 NA
4 2 1 NA
df$d4<-d1*((d2) + (d3))
df
d1 d2 d3 d4
1 2 1 1 4
2 2 1 1 4
3 2 1 NA NA
4 2 1 NA NA
What I'd like to get is this:
df2<-data.frame(d1,d2,d3,d4=c(4,4,2,2))
df2
d1 d2 d3 d4
1 2 1 1 4
2 2 1 1 4
3 2 1 NA 2
4 2 1 NA 2
I could replace all values with 0s yet that could also be misleading.
EDIT:
I've tried converting NAs to 0s but it does not work and I don't understand why.
df<-data.frame(d1,d2,d3)
df
df[is.na(df)] <- 0
df
d1 d2 d3
1 2 1 1
2 2 1 1
3 2 1 0
4 2 1 0
df$d4<-d1*((d2) + (d3))
df
d1 d2 d3 d4
1 2 1 1 4
2 2 1 1 4
3 2 1 0 NA
4 2 1 0 NA