繁体   English   中英

计算大于r中数组列中每个值的值数

[英]count the number of values greater than each value in a column of an array in r

假设我有一个数组,其中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 

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

在这里,您可以...如果您的问题用词不正确(如我在上面怀疑的那样),那么您将需要使用“ <”而不是“>”。

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM