1
我想計算矩陣中每個元素的最近鄰居(3 * 3移動窗口)的標準偏差。我在R中寫了一些代碼來實現它:計算矩陣中每個元素最近鄰的標準差的有效方法
library(FNN)
df <- matrix(1:10000, nrow = 100, ncol = 100, byrow = TRUE)
df_ <- reshape2::melt(df)
df_index <- df_[, c(1,2)]
df_query <- df_index
neighbor_index <- knnx.index(df_index, df_query, k = 9, algorithm = 'kd_tree')
neighbor_coor<- apply(neighbor_index, 1, function(x) df_query[x, ])
neighbor_sd <- lapply(neighbor_coor, function(x) sd(df[x[, 1], x[, 2]]))
sd <- do.call(rbind, neighbor_sd)
但是速度太慢。你會給我一些建議加快嗎?是否有其他方法來實現它?
我敢肯定有一個閃電'data.table'解決這個的,但你有沒有考慮'光柵套餐?也許它可能有一些幫助。 https://stackoverflow.com/questions/24068509/r-focal-raster-package-function-that-calculates-relative-to-center-cell-of-mov –
謝謝!你會寫一個簡短的代碼嗎?我會接受它作爲答案。 –