explanation of a for loop

Hi, I have some problems in understanding a for loop, maybe someone is able to help me.

This is the loop i have:

T_e <- Ta
  for (i in 1:99999) {
    v_e <- 0.6108 * exp(17.27 * T_e/(T_e + 237.3))
    T_enew <- Ta - 1 / gamma * (1 - R_ng / (lambda * Epenman.Daily)) * (v_e - vabar)
    T_e <- T_enew}

As an example this are the first five values of my data set:

Ta=c( 15.85000, 17.95000,  19.40000, 17.20000, 15.75000)
gamma = 0.06599192
 R_ng=c( 3.40699658 , 7.14502764, 4.30308424, 7.38261795, 6.40369739)
lambda=2.45
Epenman.Daily=c( 1.76016607, 2.95703213, 3.29923681, 3.01600420, 2.72208139
vabar=c( 1.2448065, 1.3487874, 1.3361953, 1.2641520, 1.2194822)

and this is the solution for T_e:
T_e:
14.54253001
17.80607304
15.99105488
17.19057572
15.42830198

My question is know, how exactly did you come to this values of T_e?
If i calculated it step by step I come to different solutions for T_e.
Maybe someone can show me, what of the data I have to put in the different equations to come to the solutions of the for loop.
Thank you very much.

This isn't a for loop.
You asked for "i", but in your code there isn't an i.

I give you an example which makes no sense, but can help you understand the mechanism:

library(tidyverse)

Ta = c(15.85000, 17.95000,  19.40000, 17.20000, 15.75000)
gamma = 0.06599192


for(i in Ta){
  
  x <- i*gamma
  print(x)
  
}

The output is

[1] 1.045972
[1] 1.184555
[1] 1.280243
[1] 1.135061
[1] 1.039373

Because every value in Ta is multiplied and printed

Ok thanks. But as it is no for loop, do you still know how the values of T_e are caluculated? How did the program come to the solutions with the code and the data I put in? When I calculate each value of T_e, I come to different outputs.

Even tough you don't use the i, the code in your loop still runs 9999 times.

At the end of the loop, you assign your result (T_enew) to T_e. Since T_e is used in the first line of the loop to calculate v_e, each new iteration of the loop uses an updated value of T_e to compute v_eand thus T_enew.
Here a simple example to ilustrate this principle:

a <- 12
for(i in 1:5){
  b <- a/2 # Do some operations based on a 
  a <- b   # assign the results of the previous line back to a
  print(a) # Just to ilustrate what happens to a in each iteration
}
#> [1] 6
#> [1] 3
#> [1] 1.5
#> [1] 0.75
#> [1] 0.375
a 
#> [1] 0.375

I think that might explain why you get a different value of T_e if you simply paste the individual values in your formula.

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.