Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of elements not being updated within loop

Tags:

r

logically this code should make sense, I'm primarily a python programmer but I'm unsure why this is not working. It is not returning any errors. What I want is for this vector of primarily zeros to be changed to a vector of only 1's and -1's (hence using the sample function). My issue is that the values of the vector are not being updated, they are just staying as 0 and I'm not sure why.

Y = numeric(100)

for (i in 100){
  x <- sample(1:2, 1)
  if (x == 2){
    Y[i] = 1
  }
  else{
    Y[i] = -1
  }
}

I've also changed the Y[i] = 1 to Y[i] <- 1 but this has not helped. I also know that x is either 1 or 2 because I test it manually using x == 2...etc

The only other issue I could think of is that x is an integer while the numbers sample returns are not but per checking this: (Note that x = 2L after the loop exited)

> typeof(x)
[1] "integer"
> typeof(2)
[1] "double"
> x == 2
[1] TRUE

I don't think it is the problem.
Any suggestions?

like image 886
Wallace Avatar asked Feb 28 '26 23:02

Wallace


2 Answers

Because the loop is just run once i.e. the last iteration. It did change in the output vector Y

tail(Y)
#[1]  0  0  0  0  0 -1

Instead it would be 1:100

for(i in 1:100)

The second issue raised is with the typeof 'x'. Here, we are sampleing an integer with 1:2 instead of a numeric vector and that returns the same type as the input. According to ?':'

For numeric arguments, a numeric vector. This will be of type integer if from is integer-valued and the result is representable in the R integer type, otherwise of type "double"

typeof(1:2)
#[1] "integer"
typeof(c(1, 2))
#[1] "double"

Another option if it is a range (:) is to wrap with as.numeric

for (i in 1:100){
  x <- sample(as.numeric(1:2), 1)
  if (x == 2){
    Y[i] = 1
  }
  else{
    Y[i] = -1
  }
}

check the type

typeof(Y)
#[1] "double"
typeof(x)
#[1] "double"
like image 118
akrun Avatar answered Mar 03 '26 17:03

akrun


Also, R is a vectorized language so this:

x<-sample(1:2, 100, replace = TRUE)
Y<-ifelse(x==2, 1, -1)

will run about 1000 times faster than your loop.

like image 35
Dave2e Avatar answered Mar 03 '26 15:03

Dave2e



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!