mynameisJEFF
mynameisJEFF

Reputation: 4239

Without for loop in R

I have a vector, which may sometimes contain 0 and 1.

I want to need to put this vector into the function qnorm

qnorm(vec , 0, 1)

However, the 0 and 1 s in vec may cause qnorm to produce -inf or inf. Now the following for loop is what I want to do to process the vector vec first, and then put the vector in qnorm function. However, I want to avoid using the for loop and the which function. Is there a more elegant solution to this ?

for(i in 1:length(vec)) {
    if(vec[i] == 0) {vec[i] <- vec[i] + 1e-50}
    else if(vec[i] == 1) {vec[i] <- vec[i] - 1e-50  }
}

Upvotes: 0

Views: 213

Answers (1)

sgibb
sgibb

Reputation: 25726

You could use ifelse:

vec <- ifelse(vec == 0, vec + 1e-50, vec - 1e-50)

If your vector contains other values than 0 and 1 you may want to use:

vec[vec == 0] <- vec[vec == 0] + 1e-50
vec[vec == 1] <- vec[vec == 1] - 1e-50

Upvotes: 1

Related Questions