【问题标题】:Efficient way to compute standard deviation of nearest neighbours of each element in matrix计算矩阵中每个元素最近邻标准差的有效方法
【发布时间】:2017-11-23 21:27:42
【问题描述】:

我想计算矩阵中每个元素的最近邻(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 可以解决这个问题,但是您考虑过raster 包吗?也许它可能会有所帮助。 stackoverflow.com/questions/24068509/…
  • 谢谢!你会写一个简短的代码吗?我会接受它作为答案。

标签: r performance matrix standard-deviation


【解决方案1】:

正如@romanlustrik 在他的评论中提出的,我们可以使用raster::focal() 来解决这个问题。

library(raster)

df <- matrix(1:10000, nrow = 100, ncol = 100, byrow = TRUE)
dfR <- raster(df)

dfSD <- as.matrix(focal(dfR, w = matrix(1,3,3), fun = sd))

其中,w 是一个矩阵,表示最近的邻居及其在fun 内的权重(在本例中为 3x3,即单元格本身和 8 个邻居)。因此,任何邻域模式都是可以想象的,只要它可以用矩阵来表示。

matrix(1,3,3)
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    1    1    1
# [3,]    1    1    1

只有 4 个邻居(不包括对角线和单元格本身)的示例:

matrix(c(0,1,0,1,0,1,0,1,0), 3, 3)
#      [,1] [,2] [,3]
# [1,]    0    1    0
# [2,]    1    0    1
# [3,]    0    1    0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 2013-07-02
    • 2013-09-11
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多