2015-05-10 21 views
2

我想將一個IDW(反距離權重)應用於數據庫中的不同組。我正在嘗試使用dplyr將這個函數應用到每個組,但是我在Split-Apply-Combine中犯了一個錯誤。當前函數爲10個觀察值的每個組返回10個值,但是當前dplyr嘗試在每個突變單元格中插入10個返回值,而不是針對突變單元格的一個新值。dplyr - 應用函數後出現的錯誤信息

該問題可能是函數不可知的,但我不幸找不到一個更簡單的函數來展示相同的錯誤。

我得到錯誤消息,數據幀已損壞,並且新列填充了值。

group N  Lat  Long Obs idw_val 
1  A 1 49.43952 20.42646 11 <dbl[10]> 
2  B 1 49.76982 19.70493 8 <dbl[10]> 

這個例子有希望澄清這一點。該解決方案可能是非常簡單的 - 一些幫助我非常感謝......

require(ggmap) 
require(dplyr) 
require(raster) 
require(sp) 
require(gstat) 
require(lattice) 

####create dataset 
set.seed(123) 
dh = expand.grid(group = c("A","B","C"), 
       N=1:10) 

dh$Lat=rnorm(nrow(dh),50,1) 
dh$Long=rnorm(nrow(dh),20,1) 
dh$Obs=rpois(nrow(dh),10) 
dh 

#####create grid 
pixels <- 10 

#####function defintion 
idw_w=function(x,y,z){ 

    geog2 <- data.frame(x,y,z) 
    coordinates(geog2) = ~x+y 

    geog.grd <- expand.grid(x=seq(floor(min(coordinates(geog2)[,1])), 
           ceiling(max(coordinates(geog2)[,1])), 
           length.out=pixels), 
          y=seq(floor(min(coordinates(geog2)[,2])), 
           ceiling(max(coordinates(geog2)[,2])), 
           length.out=pixels)) 

# Assigning coordinates results in spdataframe. 
    grd.pts <- SpatialPixels(SpatialPoints((geog.grd))) 
    grd <- as(grd.pts, "SpatialGrid") 

##### IDW interpolation. 
    geog2.idw <- idw(z ~ 1, geog2, grd, idp=4) 

####overlay 
    pts <- SpatialPoints(cbind(x, y)) 
    over(pts, geog2.idw["var1.pred"]) 
} 

#### test function 
idw_w(dh$Lat,dh$Long,dh$Obs) 

####groupwise dplyr 
dh2 = dh %>% 
    # arrange(Block, Species, Date) %>% 
    group_by(group) %>% 
    mutate(idw_val=idw_w(x=Lat,y=Long,z=Obs)) 

dh2 
str(dh2) 

回答

0

如果我知道你想什麼正確的,它只是一個做的事情確保你的函數返回值的載體而不是data.frame對象。我認爲這個功能會在您運行mutate()步驟時執行您想要的操作:

idw_w=function(x,y,z){ 

    geog2 <- data.frame(x,y,z) 
    coordinates(geog2) = ~x+y 

    geog.grd <- expand.grid(x=seq(floor(min(coordinates(geog2)[,1])), 
           ceiling(max(coordinates(geog2)[,1])), 
           length.out=pixels), 
          y=seq(floor(min(coordinates(geog2)[,2])), 
           ceiling(max(coordinates(geog2)[,2])), 
           length.out=pixels)) 

# Assigning coordinates results in spdataframe. 
    grd.pts <- SpatialPixels(SpatialPoints((geog.grd))) 
    grd <- as(grd.pts, "SpatialGrid") 

##### IDW interpolation. 
    geog2.idw <- idw(z ~ 1, geog2, grd, idp=4) 

####overlay 
    pts <- SpatialPoints(cbind(x, y)) 
    (over(pts, geog2.idw["var1.pred"]))[,1] 
}