Reputation: 699
In the following example, I want the value of the addition rather than NA
. How can I do that?
set.seed(7354)
a <- rbinom(1,1,.5)
x <- ifelse(a==0, rexp(1, 1/50), NA )
y <- ifelse(a==1, rexp(1, 1/100), NA)
b <- ifelse(a==1, rbinom(1,1,.5), NA)
z1 <- ifelse(b==1, rexp(1, 1/100), NA)
z2 <- ifelse(b==0, rexp(1, 1/190), NA)
s <- (1-a)*x + a *(y + b * z1 + (1-b) * z2)
My desired output is s = 968.8501
.
Upvotes: 0
Views: 49
Reputation: 57686
set.seed(7354)
a <- rbinom(1,1,.5)
x <- (a==0) * rexp(1, 1/50)
y <- (a==1) * rexp(1, 1/100)
b <- (a==1) * rbinom(1,1,.5)
z1 <- (b==1) * rexp(1, 1/100)
z2 <- (b==0) * rexp(1, 1/190)
(1-a)*x + a *(y + b * z1 + (1-b) * z2)
# [1] 968.8501
If you're doing this as part of a simulation or bootstrapping loop, this will be much faster than a bunch of ifelse
s.
Upvotes: 1
Reputation: 9313
Do this
s = c( (1-a)*x, a*y, a*b*z1, a*(1-b)*z2 )
s = sum(s, na.rm = T)
This will let you have NAs but they will not affect the sum of terms that are not.
Upvotes: 2