假设我有一个x表示重复测量的数组(1-4),y表示处理(A,B),z表示时间点(1-3)
x <- c(2,2,4,15,17,13,3,10,3,4,11,14,1,3,19,6,13,6,12,18,9,13,12,16)
dim(x) <- c(4,2,3)
, , 1
[,1] [,2]
[1,] 2 17
[2,] 2 13
[3,] 4 3
[4,] 15 10
, , 2
[,1] [,2]
[1,] 3 1
[2,] 4 3
[3,] 11 19
[4,] 14 6
, , 3
[,1] [,2]
[1,] 13 9
[2,] 6 13
[3,] 12 12
[4,] 18 16
我想创建一个新数组,其每次复制的次数都大于该治疗和时间点组合的所有其他重复次数:
, , 1
[,1] [,2]
[1,] 2 0 #both 4 and 15 are bigger then 2, so for 1,1,1 the result is 2
[2,] 2 1
[3,] 1 3 #15 is the only replicate bigger than 4 so result for 3,1,1 is 1
[4,] 0 2
, , 2
[,1] [,2]
[1,] 3 3
[2,] 2 2
[3,] 1 0
[4,] 0 1
, , 3
[,1] [,2]
[1,] 1 3
[2,] 3 1
[3,] 2 2
[4,] 0 0
答案 0 :(得分:1)
apply
可以做到这一点,在每一栏(2)和阶层(3)内行动:
## recreate your data array:
arr <- c(2,2,4,15,17,13,3,10,3,4,11,14,1,3,19,6,13,6,12,18,9,13,12,16)
dim(arr) <- c(4,2,3)
## one liner using apply
apply(arr, 2:3, function(x) sapply(x, function(y) sum(y < x) ) )
#, , 1
#
# [,1] [,2]
#[1,] 2 0
#[2,] 2 1
#[3,] 1 3
#[4,] 0 2
#
#, , 2
#
# [,1] [,2]
#[1,] 3 3
#[2,] 2 2
#[3,] 1 0
#[4,] 0 1
#
#, , 3
#
# [,1] [,2]
#[1,] 1 3
#[2,] 3 1
#[3,] 2 2
#[4,] 0 0
答案 1 :(得分:0)
这里你去......如果你的问题是错误的措辞(我上面怀疑),那么你需要使用&#34;&lt;&#34;而不是&#34;&gt;&#34;。
a <- array(rnorm(24), dim= c(4,2,3))
cnts <- function(a) {
a2 <- array(NA, dim= dim(a))
for (i in 1:dim(a)[3]) {
for (j in 1:dim(a)[2]) {
for (k in 1:length(a[,j,i])) {
a2[k,j,i] <- sum(a[k,j,i] > a[,j,i])
}
}
}
return(a2)
}