简体   繁体   中英

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

Say I had an array with x representing repeat measurements (1-4), y representing treatments (A,B) and z representing timepoints (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

I want to create a new array that has the number of times each replicate is greater than all other replicates for that treatment and timepoint combination:

, , 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 can do this, acting within each column (2) and strata (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

Here you go... If you're question is incorrectly phrased (as I suspect above), then you will need to use "<" instead of ">".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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