2017-04-11 66 views
0

真的很感激我的整頓問題R.45度翻轉

我已經寫在R A KDE功能,我使用MASS :: kde2d作爲我的參考任何幫助,繪製和示範犯罪數據。我所生產的密度值似乎在正確的範圍內,以及密度的整體分佈,但它似乎通過地塊原點翻轉了45度。

請注意下圖中的形狀幾乎相同,但翻轉。

Right plot: kde2d function. Left plot: my Kernel2D function

任何幫助將不勝感激!如果任何人都可以發現錯誤,我在下面附加了我的2D功能。謝謝!

該函數的輸入是一個空間點陣,座標位於網格單元的中心,犯罪點的緯度和經度順序,帶寬h和開關參數。我正在考慮包括其他內核因此包含。

Kernel2D <- function(lattice, crime.locations, h, kernel){ 
    if(is.data.frame(spatial.lattice)==FALSE) {lattice <- data.frame(lattice)} 

    d <- fields::rdist(lattice, crime.locations) 

    switch(kernel, 


     'normal'={ 
      k=1 
      cat('k = 1, then rescaled so sum of densities = N. ') 
      cat("Normal - Function extends to boundary in all directions, applied to every location in the region regardless of h") 

## This is the density calculation which iterates through the rows of d. I.e. for 
## each cell in the lattice, it does a calculation on that row where the row contains the 
## distances from that cell to each crime location. (Not trying to patronize anyone here 
## with having dumb explanations! Trying to make it simple so I may understand it myself 
## when explaining it to others haha) . 
## I have assumed that this is correct as it it producing the same density shape as MASS::kde2d. 
## There is an error when associating the density values to the right grid. Hmm. Ill have more of a think now. 

      density <- apply(d, 1, function(x) sum((1/(2*pi*h**2))*exp(-(x**2)/(2*h**2)))) 
      k = nrow(crime.locations)/sum(density) 
      density <- k*density}, 

     stop('Kernel Undefined. Available: triangular, uniform, negexp, normal, quartic')) 

    return(density)} 

回答

0

我想我可能找到了發生這種情況的原因。

因此,當我繪圖時,將密度值與正確的網格關聯顯然存在一些錯誤。

所以在函數中,我可能會逐行計算一個格,它將返回一個列向量(逐行排列)。我可能將此向量附加到數據框(例如),但df中單元格的行不是在行中按行排序,而是實際上逐列排列。因此,當我爲繪圖設置數據時,我將密度附加到錯誤的網格上。如果行與列的理論是正確的,這將產生一個將被翻轉的情節。

啊哈,這可能是問題。我將改變我的函數,將密度附加到網格中作爲其計算,以便正確的網格獲得正確的密度。當我嘗試過這個時會回覆給你更新!