Alex Kors
Alex Kors

Reputation: 202

IF statement inside the FOR loop

I'm trying to right a function that would take all the elements which are more than 0.5 or less than -0.5 from rnorm(), double it and return it into a vector.

zzz<-function(xxx=2){
    zz<-rnorm(1000)

    maxi<-zz>0.5
    mini<-zz<-0.5

    for (i in 1:zz){
           if (maxi==TRUE | mini==TRUE){       
          yyy<-xxx*zz[i]
          count<-append(count,yyy)
                   }
    }
count
}

I'm very new to this. Any help will be much appreciated. Thank you

Upvotes: 0

Views: 132

Answers (2)

James King
James King

Reputation: 6365

Using a loop in this way is not idiomatic R. R is a vectorized language which means loops are not needed to do arithmetic on vectors. I recommend reading An Introduction to R to get familiar with the standard approaches.

Also I don't think it's optimal to compute your random vector inside the function (it will make it hard to debug); maybe you want to pass it as an argument.

The following code will do what you want:

v <- rnorm(5)
v

[1] -2.078349536  0.004373942  0.269364879  0.199779240  0.373235666

ind <- which(v < -0.5 | v > 0.5)
v[ind] <- v[ind] * 2
v

[1] -4.156699071  0.004373942  0.269364879  0.199779240  0.373235666

Maybe a function like this would make sense:

twiddle <- function(v, multiplier = 2) {
  ind <- which(v < -0.5 | v > 0.5)
  v[ind] <- v[ind] * multiplier
  return(v)
}

Or more compactly, just v[abs(v) > 0.5] <- v[abs(v) > 0.5] * multiplier; return(v) as pointed out in the comment.

Called like this:

u <- rnorm(1000)
twiddle(u)

Upvotes: 3

alittleboy
alittleboy

Reputation: 10956

You can try the following codes which ask for an argument of the number of samples to be generated:

my.func = function(n=1000){
  rn = rnorm(n)
  good = rn[rn > 0.5 | rn < -0.5]
  return(2*good)
}

Run my.func(1000) to get the vector.

Upvotes: 2

Related Questions