gpt4 book ai didi

R:将矩阵拆分为任意数量的 block

转载 作者:行者123 更新时间:2023-12-04 05:56:42 25 4
gpt4 key购买 nike

假设我有一个值矩阵

    set.seed(1)
A <- matrix(runif(25),ncol=5)

我想计算这个近似相等大小的矩阵内近似正方形邻域的一些统计数据。这两种输出中的任何一种都可以:
    N1 <-  matrix(c(rep(c("A","A","B","B","B"),2),rep(c("C","C","D","D","D"),3)),ncol=5)
N2 <- matrix(c(rep(c("A","A","A","B","B"),3),rep(c("C","C","D","D","D"),2)),ncol=5)
N1
[,1] [,2] [,3] [,4] [,5]
[1,] "A" "A" "C" "C" "C"
[2,] "A" "A" "C" "C" "C"
[3,] "B" "B" "D" "D" "D"
[4,] "B" "B" "D" "D" "D"
[5,] "B" "B" "D" "D" "D"

N2
[,1] [,2] [,3] [,4] [,5]
[1,] "A" "A" "A" "C" "C"
[2,] "A" "A" "A" "C" "C"
[3,] "A" "A" "A" "D" "D"
[4,] "B" "B" "B" "D" "D"
[5,] "B" "B" "B" "D" "D"

其他近似值也可以,因为我总是可以旋转矩阵。然后我可以使用这些邻域矩阵来计算统计数据 tapply() , 像这样:
    tapply(A,N1,mean)
A B C D
0.6201744 0.5057402 0.4574495 0.5594227

我想要的是一个函数,它可以使我成为具有任意数量的块状邻域的任意维度矩阵,例如 N1N2 .我很难弄清楚这样一个函数如何处理所需数量的块甚至不是正方形的情况。 N1N2有 4 个街区,但说我想要 5 个这样的输出:
    N3 <-  matrix(c("A","A","B","B","B","A","A","C","C","C","D","D","C","C","C",
"D","D","E","E","E","D","D","E","E","E"),ncol=5)
[,1] [,2] [,3] [,4] [,5]
[1,] "A" "A" "D" "D" "D"
[2,] "A" "A" "D" "D" "D"
[3,] "B" "C" "C" "E" "E"
[4,] "B" "C" "C" "E" "E"
[5,] "B" "C" "C" "E" "E"

有谁知道可以进行这种拆分的现有功能,或者对如何制作一个功能有任何想法?谢谢!

[[编辑]]
我的最终功能,考虑到文森特的建议:
    DecideBLocks <- function(A,nhoods){
nc <- ncol(A)
nr <- nrow(A)
nhood_side <- floor(sqrt((nc*nr)/nhoods))
Neighborhoods <- matrix(paste(ceiling(col(A)/nhood_side), ceiling(row(A)/nhood_side), sep="-"), nc=ncol(A))
nhoods.out <- length(unique(c(Neighborhoods)))
if (nhoods.out != nhoods){
cat(nhoods.out,"neighborhoods created.\nThese were on average",nhood_side,"by",nhood_side,"cells\nit's a different number than that stated the function tries to round things to square neighborhoods\n")
}
return(Neighborhoods)
}
A <- matrix(rnorm(120),12)
B <- DecideBLocks(A,13)

最佳答案

你可以试试玩rowcol职能:
他们将问题简化为一维问题。
下面定义了大小最多为 2*2 的块。

matrix( 
paste(
ceiling(col(A)/2),
ceiling(row(A)/2),
sep="-"),
nc=ncol(A)
)

关于R:将矩阵拆分为任意数量的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9430950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com