r - Is it possible to skip NA values in "+" operator? -


i want calculate equation in r. don't want use function sum because it's returning 1 value. want full vector of values.

x = 1:10 y = c(21:29,na) x+y  [1] 22 24 26 28 30 32 34 36 38 na  x = 1:10 y = c(21:30) x+y  [1] 22 24 26 28 30 32 34 36 38 40 

i don't want:

sum(x,y, na.rm = true) [1] 280 

which not return vector.

this toy example have more complex equation using multiple vector of length 84647 elements.

here example of mean:

x = 1:10 y = c(21:29,na) z = 11:20 = c(na,na,na,30:36) 5 +2*(x+y-50)/(x+y+z+a)   [1]       na       na       na 4.388889 4.473684 4.550000 4.619048 4.681818 4.739130       na 

1) %+% define custom + operator:

`%+%` <- function(x, y)  mapply(sum, x, y, moreargs = list(na.rm = true)) 5 + 2 * (x %+% y - 50) / (x %+% y %+% z %+% a) 

giving:

[1] 3.303030 3.555556 3.769231 4.388889 4.473684 4.550000 4.619048 4.681818 [9] 4.739130 3.787879 

here simple examples:

1 %+% 2 ## [1] 3  na %+% 2 ## [1] 2  2 %+% na ## [1] 2  na %+% na ## [1] 0 

2) na2zero possibility define function maps na 0 this:

na2zero <- function(x) ifelse(is.na(x), 0, x)  x <- na2zero(x) y <- na2zero(y) z <- na2zero(z) <- na2zero(a)  5 + 2 * (x + y - 50) / (x + y + z + a) 

giving:

[1] 3.303030 3.555556 3.769231 4.388889 4.473684 4.550000 4.619048 4.681818 [9] 4.739130 3.787879 

3) combine above variation combining (1) idea in (2) is:

x <- x %+% 0 y <- y %+% 0 z <- z %+% 0 <- %+% 0  5 + 2 * (x + y - 50) / (x + y + z + a) 

4) numeric0 class can define custom class "numeric0" own + operator:

as.numeric0 <- function(x) structure(x, class = "numeric0") `+.numeric0` <- `%+%`  x <- as.numeric0(x) y <- as.numeric0(y) z <- as.numeric0(z) <- as.numeric0(a)  5 + 2 * (x + y - 50) / (x + y + z + a) 

note: inputs used in question, namely:

x = 1:10 y = c(21:29,na) z = 11:20 = c(na,na,na,30:36) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -