【问题标题】:45 degree flip with 2d Normal Kernel Density45 度翻转,具有 2d 法线核密度
【发布时间】:2017-09-06 23:02:43
【问题描述】:

非常感谢您在 R 中纠正我的问题的任何帮助。

我在 R 中编写了一个 KDE 函数,我使用 MASS::kde2d 作为参考,来绘制和建模犯罪数据。我产生的密度值似乎在正确的范围内,以及密度的整体分布,但它似乎通过绘图原点翻转了 45 度。

请注意下图中的形状几乎相同,但翻转了。

任何帮助将不胜感激!如果有人能发现错误,我在下面附上了我的 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)}

【问题讨论】:

    标签: r kde


    【解决方案1】:

    我想我可能找到了发生这种情况的原因。

    因此,当我在绘图时,将密度值与正确的网格相关联显然存在一些错误。

    所以在函数中我可能会逐行计算一个格子,它返回一个一列向量(按行顺序)。我可能会将此向量附加到数据框(例如),但 df 中的单元格行在格中不是逐行排列的,它们实际上是逐列排列的。因此,当我设置用于绘图的数据时,我将密度附加到错误的网格上。如果行与列理论是正确的,这将产生一个将被翻转的图。

    啊哈,这可能是问题所在。我将更改我的函数以将密度附加到网格作为其计算,以便正确的网格获得正确的密度。当我尝试这个时会尽快回复你!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2017-05-09
      • 2020-04-30
      • 2016-02-27
      • 1970-01-01
      相关资源
      最近更新 更多