upabove
upabove

Reputation: 1119

apply ifelse() to each element of vector

I have a vector:

a<-rnorm(100,0,1)

I would like to do the following:

  1. generate a random number rnorm(1)
  2. if the random number is smaller than a specified constant (e.g. 0.5), then add 1 to the a[x] if it is larger keep a[x]: if (rnorm(1) < 0.5) a[x]+1 else a[x]

  3. do this for each element of a.

I was thinking of using ifelse()

ifelse( rnorm(1)<0.5, a[x]+1, a[x]), however, this only returns a single element as output.

I was also thinking of combining it with sapply:

sapply(1:length(a), function(x) if(rnorm(1)<0.5) a[x]+1 else a[x]), however, I'm not sure how to use if statements within sapply().

Can someone help?

Update:

and what if instead of wanting to add 1 to a[x] I would like to add a[x]+runif(1)

ifelse(rnorm(length(a)<0.5, a[x]+runif(1), a[x])

this would add the same random number of each element of a[x] that satisfies the condition. is it possible to vectorize this second part?

Upvotes: 2

Views: 4721

Answers (1)

Thomas
Thomas

Reputation: 44525

Why not just a + rbinom(100,1,.5)?

If you need to use ifelse, the problem is you didn't vectorize your call to rnorm:

ifelse( rnorm(length(a))<0.5, a+1, a)

Upvotes: 2

Related Questions