0

I am using a function to grab data from our organization server which then need to be stored in an empty data.frame through a for loop. The data is for March 01 to May 31 (92 days) for 130 different sites (130 columns for the sites while 1 column for the date).

tss <- as.data.frame(matrix(NA, 92,131))

The function itself works. The for loop also works for the first 14 stations but then it spit out the following error

> Error in `[<-.data.frame`(`*tmp*`, , i + 1, value = c(0, 0, 0, 0, 0,
> 0,  :    replacement has 90 rows, data has 92

The for loop that i am using to populate the empty matrix is as follow

for (i in 1:nlines) {
      tss1 <- fromAquarius(id[i],Data[i],Stage[i])
  tss[,i+1]<-tss1$Daily_sum
  rm(tss1)
    }

Is there a way to let the code run and fill in the matrix with available data and leaving the cell as NA if there is no data while moving forward? There could be another way to handle the error.

Hydro
  • 1,057
  • 12
  • 25
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. What exactly does the `fromAquarius` function return? – MrFlick Mar 30 '20 at 01:40
  • `FromAquarius` is a `function` (a lengthy one) that would return value for a given station. – Hydro Mar 30 '20 at 01:44

1 Answers1

0

Without knowing the details of fromAquarius it is difficult to debug why this is happening. However, we can add a check that add as a new column only if length of values to be added is exactly the same as number of rows or else add NA.

for (i in 1:nlines) {
   tss1 <- fromAquarius(id[i],Data[i],Stage[i])
   tss[,i+1]<-tss1$Daily_sum[1:92]
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks @Ronak shah, the code now runs and return `tss` filled with values, however, there are multiples columns that are populated with `NA`. I can share the function `FromAquarius` if you would like to have a look. However, it won't grab the data for you as this needs to be run on a dedicated machine linked to our organization server. – Hydro Mar 30 '20 at 02:53
  • Can you check the updated answer? It adds `NA` when the length is less than 92. – Ronak Shah Mar 30 '20 at 02:58
  • Yes- it adds NA when length is less than 92. I guess it address my problem. Thank you so much. i am going to accept this an answer – Hydro Mar 30 '20 at 03:16