简体   繁体   English

在函数中使用R替换for循环

[英]replace for loop with apply in R within a function

I have created a function which requires a raster and a matrix.Every row of the matrix holds the coordinates of a cell in the raster. 我创建了一个需要栅格和矩阵的函数。矩阵的每一行都包含栅格中单元格的坐标。 After finishing my function returns a vector which contains the number of every cell that is saved in my matrix via it's coordinates: 完成我的函数后,返回一个向量,该向量包含通过它的坐标保存在矩阵中的每个单元格的数量:

library(raster)
library(gdistance)
r <- raster(nrow=100,ncol=15)
r[] <- 1:ncell(r)
plot(r)
pts <- matrix(c(-144,72.9,-168,45.9,-144,13.5),ncol=2,nrow=3,byrow=TRUE)

get_cells <- function(raster,points_matrix) {
Cells <- c()
for (i in 1:nrow(points_matrix))
    {
    Cells[i] <- cellFromXY(raster,c(points_matrix[i,]))
    }
    return(Cells)

}

Now I would like to restructure my function so that I can use it with apply() . 现在我想重构我的函数,以便我可以使用apply() So in the end I want to be able to type something like: 所以最后我希望能够输入如下内容:

apply(pts,1,get_cells)

and get the same result, but I can't figure out how to do it. 得到相同的结果,但我无法弄清楚如何做到这一点。 Any kind of help is highly appreciated. 任何形式的帮助都非常感谢。

You can define one line function within apply function. 您可以在apply函数中定义一个线函数。 Try this 尝试这个

apply(pts,1,function(x) return(cellFromXY(raster,x)))

EDIT: @snoops apply does takes user defined functions also like yours. 编辑:@snoops apply确实采用与您类似的用户定义函数。 Your Problem is you have two input arguments in your function while your code with apply you are providing only one argument. 你的问题是你的函数中有两个输入参数,而你的代码只提供一个参数。 And you do not need loop inside your function. 而且你的函数内部不需要循环。

get_cells <- function(x,raster) {
    Cells <- cellFromXY(raster,x)
    return(Cells)
}

Now this will work. 现在这将有效。 You can give other arguments of your function inside apply function itself like this. 您可以像这样在apply函数本身中给出函数的其他参数。

apply(pts,1,getCells,raster = r)

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

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