I'm fairly new to R and have run into an issue with NA's. This question may have been answered elsewhere but I can't seem to find the answer. I'm trying to do sort of the opposite of rowSums()
in that I'm trying to subtract x2
and x3
from x1
in order to generate x4
without NA's. The code I'm currently using is as follows:
> x <- data.frame(x1 = 3, x2 = c(4:1, 2:5), x3=c(1,NA))
> x$x4=x$x1-x$x2-x$x3
> x
x1 x2 x3 x4
1 3 4 1 -2
2 3 3 NA NA
3 3 2 1 0
4 3 1 NA NA
5 3 2 1 0
6 3 3 NA NA
7 3 4 1 -2
8 3 5 NA NA
In other words I want to ingore the NA's similar to how rowSums
allows the na.rm=TRUE
argument so that I get this result:
x1 x2 x3 x4
1 3 4 1 -2
2 3 3 NA 0
3 3 2 1 0
4 3 1 NA 2
5 3 2 1 0
6 3 3 NA 0
7 3 4 1 -2
8 3 5 NA -2
Any help is greatly appreciated.