eco-detectives / eco_detective

Reading/coding group for The Ecological Detective
1 stars 3 forks source link

Is my R acting funny or I'm doing it wrong? #7

Closed stapial closed 6 years ago

stapial commented 6 years ago

Hi guys,

I haven't been able to pull a successful for loop in all day and it's getting frustrating. I have noticed that my R only returns result for the first iteration, no matter what I do.

Here's what I'm trying to do for pseudocode 4.1, part 2. It only returns U for the first iteration

for(i in TowVec){
  Uvec <- vector(length=length(TowVec))
  Uvec[1] <- runif(n=1,min=0,max=1)
  cat('i = ', i, ' U = ', Uvec[i])
  Uvec[i+1] <- runif(n=1,min=0,max=1) 
}

I've been having the same outcome in every loop, so I did a simple one. Again, only the first iteration returns a value. I'm using the same procedure than always. Today I updated to R 3.5 and that's when it started acting funny. Any chance is R giving me a hard time or is it me doing it wrong??

for (i in seq(1:20)){
  yvec <- vector(length=length(1:20))
  yvec[1] <- 2
  yvec[i+1] <- yvec[i]*2
  cat('i = ', i, ' y = ', yvec)
  return(yvec)
}

i = 1 y = 2 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

oharac commented 6 years ago

hint: at what point are you initializing your vector Uvec, and your initial value Uvec[1]?

stapial commented 6 years ago

think I figured it out. Thanks!