1

I have a data frame with daily observations, which I would like to interpolate. I use automap to build a variogram for every days and then apply on new data. I try to run a loop and put the results in a new dataframe. Unfortunately, the data frame with the results only contains the last predicted day.

coordinates(mydata) <- ~lat+long
coordinates(new_data) <- ~lat+long
df <- data.frame(matrix(nrow=50,ncol=10)) #new data frame for predicted valeus

for(i in 1:ncol(mydata))
    kriging_new <- autoKrige(mydata[,i],mydata,newdata)
    pred <- kriging_new$krige_output$var1.pred
    df[,i] <- data.frame(pred)

The result looks like this, all the columns should be filled with values, not just the last one:

X1 X2 X3 X4 X5 X6 X7 X8 X9       X10
1  NA NA NA NA NA NA NA NA NA 12.008726
2  NA NA NA NA NA NA NA NA NA  6.960499
3  NA NA NA NA NA NA NA NA NA 10.894787
4  NA NA NA NA NA NA NA NA NA 14.378945
5  NA NA NA NA NA NA NA NA NA 17.719522

I also get a warning, saying:

Warning message:
In autofitVariogram(formula, data_variogram, model = model, kappa = kappa,  :
  Some models where removed for being either NULL or having a negative sill/range/nugget, 
    set verbose == TRUE for more information

If I do autoKrige manually for each row, everything works fine. It seems the loop is not working as it usually does. Is this some problem in the automap package?

Thanks a lot!

Tom
  • 25
  • 4

1 Answers1

2

I think you just forgot to enclose the code in your for loop in curly brackets. As a result you execute the loop 10 times, overwriting kriging_new with itself every time:

for(i in 1:ncol(mydata))
    kriging_new <- autoKrige(mydata[,i],mydata,newdata)

Only then do you assign the result from your last iteration:

pred <- kriging_new$krige_output$var1.pred

and finally assign those to the last column of your data frame holding your predictions (the loop counter i is still set to 10 at this point):

df[, i] <- data.frame(pred)

Always write loops with multiple lines of statements like this:

for (condition) {
    statement1
    statement2
    ...
}
Roland Seubert
  • 315
  • 3
  • 9
  • Right! Thanks a lot! Tried to figure this out for too long, must have been totally brackets blind :-) It works now! – Tom Oct 05 '14 at 22:42