For loop stops after n steps

Hi everyone!
I have a for loop that applies a function ("f_richards") on a value ("vol") and sums the result of the function to the result of the previous loop (it is a function that calculates an increment based on the initial volume).
The code should perform a different time of loops for each row, where the number of loops is specified in the column "diff". The aim is to fill the last column (vol2020) with the result of the initial volume + n increments.

I used it on small data frames and it works properly but when I use it on bigger data frames (360 and 380 rows) it stops at a certain point (67th and 79th row). An error occurs:

Error in x[[jj]][iseq] <- vjj : replacement has length zero

The loop is the following:

for( i in 1:nrow(crescitaHP1)){
  for ( j in 1:crescitaHP1$diff[i]){
    crescitaHP1[i,2+2*(j-1)+1]= f_richards(crescitaHP1[i,2+2*(j-1)], crescitaHP1[i,ncol(crescitaHP1)-1])
    crescitaHP1[i,2+2*(j-1)+2]=crescitaHP1[i,2+2*(j-1)]+crescitaHP1[i, 2+2*(j-1)+1]
    crescitaHP1[i,ncol(crescitaHP1)]<-crescitaHP1[i,2+2*(j-1)+2]
  }}

and it is applied on a dataframe (crescitaHP1) which has the following columns:

diff       vol          2*max(rip) blank columns            ID            sp_gov         vol2020

where "diff" is the number of loops to perform per row, "vol" is the initial volume, the number of blank columns has the size useful to be compiled with increment and new volume for each loop, "sp_gov" is a parameter of the function "f_richards" and "vol2020" is the final field I want to be compiled.

Do you have any idea of why it suddenly stops? Thank you so much! Hope I managed to explain it clearly

it stops because the replacement value vjj has zero (i.e. no length) and so x[[jj]][iseq] cannot be replaced by it.
Here is an example

(example_vector <-  1:2)
(my_replacement <- 3)
# set entry one of example vector to the new value
example_vector[1] <- my_replacement  # works fine
example_vector # see :) 
(my_replacement <- NULL)  # improper replacement value
example_vector[1] <- my_replacement  # errors

Further thoughts : if it's correct that vjj should have no informational content at that position. then have it be an NA value, which therefore can be stored without error.
i.e.

(my_replacement <- NA)  # would work
example_vector[1] <- my_replacement 

otherwise revisit how vjj is calculated and correct it so it gives an appropriate value

Thank you! I got the problem: the function "f_richards" found non-valid parameters in correspondence with the row the loop stopped. I'm fixing those values and now the loop works.

Thank you!

1 Like

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.