简体   繁体   中英

In R, how can I get the value of an addition rather than NA

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM