简体   繁体   中英

R apply with custom functions

I'm having trouble applying a custom function in R. The basic setup is I have a bunch of points, I want to drop a grid over top and get the max z value from each cell.

The code I'm trying is below. The results I'm looking for would return myGrid$z=c(5,10,na). The na could be a different value as well as long as I could filter it out later. I'm getting an error at the apply stage

I believe there is an error in how I'm using apply, but I just haven't been able to get my head wrapped around apply.

thanks, Gordon

myPoints<-data.frame(x=c(0.7,0.9,2),y=c(0.5,0.7,3), z=c(5,3,10))
myGrid<-data.frame(x=c(0.5,2,4),y=c(0.5,3,10))
grid_spacing = 1

get_max_z<-function(x,y) {
    z<-max(myPoints$z[myPoints$x > (x-grid_spacing/2)
        & myPoints$x <= (x+grid_spacing/2)
        & myPoints$y > (y-grid_spacing/2)
        & myPoints$y <= (y+grid_spacing/2)])
            return(z)
}

myGrid$z<-apply(myGrid,1,get_max_z(x,y),x=myGrid$x,y=myGrid$y)

Edited to include the return(z) line I left out. added $y to line of custom function above return.

First of all I would recommend you to always boil down a question to its core instead of just posting code. But I think I know what your problem is:

> df <- data.frame(x = c(1,2,3), y = c(2,1,5))

> f <- function(x,y) {x+y}

> apply(df,1,function(d)f(d["x"],d["y"]))
[1] 3 3 8

apply(df,1,.) will traverse df row wise and hand the current row as an argument to the provided function. This row is a vector and passed into the anonymous function via the only available argument d . Now you can access the elements of the vector and hand them further down to your custom function f taking two parameters.

I think if you get this small piece of code then you know how to adjust in your case.

UPDATE:

Essentially you make two mistakes:

  1. you hand a function call instead of a function to apply.

    function call: get_max_z(x,y)

    function: function(x,y)get_max_z(x,y)

  2. you misinterpreted the meaning of "..." in the manual to apply as the way to hand over the arguments. But actually this is just the way to pass additional arguments independent of the traversed data object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM