Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 具有2d正常内核密度的45度翻转_R_Kde - Fatal编程技术网

R 具有2d正常内核密度的45度翻转

R 具有2d正常内核密度的45度翻转,r,kde,R,Kde,如果您能帮我解决R的问题,我将不胜感激 我已经在R中编写了一个KDE函数,我使用MASS::kde2d作为我的参考,来绘制和建模犯罪数据。我正在生成的密度值似乎在正确的范围内,以及密度的总体分布,但它似乎在绘图原点翻转了45度 请注意,在下图中,形状几乎相同,但已翻转 任何帮助都将不胜感激!如果有人能发现错误,我会在下面附上我的2d函数。谢谢大家! 该函数的输入是一个空间晶格,坐标位于网格单元的中心,犯罪地点在纬度,然后是经度顺序,带宽h和一个开关参数。我正在考虑将其他内核包括在内 Kerne

如果您能帮我解决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)}

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

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

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

啊哈,这可能就是问题所在。我将更改我的函数,在计算时将密度附加到网格,以便正确的网格获得正确的密度。当我尝试此功能后,会给你一个更新