简体   繁体   English

R与自定义函数一起应用

[英]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. 我在R中应用自定义函数时遇到问题。基本设置是我有很多要点,我想在顶部放一个网格并从每个单元格中获取最大z值。

The code I'm trying is below. 我正在尝试的代码如下。 The results I'm looking for would return myGrid$z=c(5,10,na). 我要寻找的结果将返回myGrid $ z = c(5,10,na)。 The na could be a different value as well as long as I could filter it out later. na可以是其他值,只要稍后可以过滤掉即可。 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. 我认为我在使用Apply的方式上存在错误,但是我只是无法将自己的头缠在APP上。

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. 编辑以包括我遗漏的return(z)行。 added $y to line of custom function above return. 在返回上方的自定义函数行中添加了$ y。

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. apply(df,1,.)将逐行遍历df并将当前行作为所提供函数的参数。 This row is a vector and passed into the anonymous function via the only available argument d . 该行是向量,并通过唯一可用的参数d传递给匿名函数。 Now you can access the elements of the vector and hand them further down to your custom function f taking two parameters. 现在,您可以访问向量的元素,并使用两个参数将它们进一步传递给自定义函数f。

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) 函数调用: get_max_z(x,y)

    function: function(x,y)get_max_z(x,y) 函数: 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. 但是实际上,这只是传递独立于遍历数据对象的其他参数的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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