rgstat

Adding an argument to a mathematical function


I'm trying to automate a process to produce interpolated geochemical maps. I've created a loop that essentially starts at column #13 and loops through until #67.

However, part of the IDW code requires the header of the current column for the respective geochemical parameters to be mapped.

For instance; column #13's header is "Ag_ppm", so the original code read:

    LogSr.idw = idw(log10("Ag_ppm") ~ 1 , locations=NGSA.SPDF, newdata=NGSA.grid,
                   maxdist=15000, nmin=4)

I've been able to obtain the header of the column in interest within each loop using (where i increases by 1 each loop; 13, 14, 15 etc.):

    coln <- colnames(NGSA.df[i])

However, when I simply substitute the "Ag_ppm" to coln, the line fails with a given error. I've tried various approaches including paste, although everything still results in the same error.

    LogSr.idw = idw(log10(coln) ~ 1, locations=NGSA.SPDF, newdata=NGSA.grid,
                    maxdist=15000, nmin=4) 

Error in log10(coln) : non-numeric argument to mathematical function

Is there a reasonably simple approach using the current method?


Solution

  • It is surprising to me that log10("Ag_ppm") doesn't throw the same error, but I have often overcome this problem using get:

    LogSr.idw = idw(log10(get(coln)) ~ 1, locations=NGSA.SPDF, newdata=NGSA.grid,
                    maxdist=15000, nmin=4)
    

    In most situations, it is a good idea to think of an alternative to using get, but due the the formula (~) here, and the use of the newdata arguemtn, get might be the best solution.