0

I am beginner in R so when I tried to make a for loop by sequence it gave me the expected result for one vector but for the second one, it gave me the same value along the vector (It made only the first iteration )

moyenne<- c()
ecart<-c()
for(i in seq(1,length(vector1), by=nbsim)){
  moyenne<-c(moyenne, mean(P_totale-GRAVE- ATTRITIONNEL-vector2[i:i+nbsim-1]+vector1[i:i+nbsim-1])) 
  #mean of the result
  ecart<-c(ecart,sqrt(var(vector1[i:i+nbsim-1]-vector2[i:i+nbsim-1]-ATTRITIONNEL-GRAVE+P_totale)))
  #standard deviation of the result
}
moyenne
ecart

vector1 and vector 2 have the same length which is equal to 90000, P_totale, GRAVE and ATTRITIONNEL are vectors with length=nbsim My problem was with the vector "ecart", I didn't know why it gave me the same value, could someone help me, please ?

wej
  • 21
  • 1
  • 2
    Welcome to StackOverflow. Please take the [tour] and see [ask]. Since R is a language specific to data science, we need data not just code. Fortunately R has the `dput` function which dumps objects to ascii format that we can run on our end to regenerate your data. Please [**edit**](https://stackoverflow.com/posts/64229013/edit) your post with such outputs. We do not need 90k values but a small enough sample like 10/20/30 to reproduce your problem. Please also see [How to make a great R reproducible example](https://stackoverflow.com/q/5963269/1422451). – Parfait Oct 06 '20 at 15:45
  • 2
    Your problem might be that `i:i+nbsim-1` is not the same as `i:(i+nbsim-1)`. – Andrew Gustar Oct 06 '20 at 15:48
  • On AndrewGustar's note, it is useful to know the "order of precedence" of operators in R. For instance, just like in arithmetic, "multiply" takes precedence over "addition". You can find the order with [`?Syntax`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html) (admittedly not the first place I would have looked had I not already known it was there). In this case, the sequence operator `:` comes *before* the binary (though not the unary) `+`, which means the addition (and subtraction) is done *after* the sequence. – r2evans Oct 06 '20 at 16:22
  • Thank you very much, I got the correct result when I added parentheses. – wej Oct 06 '20 at 17:46

0 Answers0