R: find the maximum value every two rows in every column

I want to find the maximum value in each column for every 2 rows (say). How do I do this in R? for example

matrix(c(3,1,20,5,4,12,6,2,9,7,8,7), byrow=T, ncol=3) 

      

I need an output like this

matrix(c(5,4,20,7,8,9), byrow=T, ncol=3) 

      

+3


source to share


4 answers


Here's one way to do it.

  • Define a vector containing information about the groups

    one you want. In this case, I use rep

    to repeat a sequence of numbers.
  • Then define a helper function to calculate the maximum value of an array column - this is a simple apply

    one max

    .
  • finally, use sapply

    with an anonymous function that applies colMax

    grouped arrays to each of your subsets.

Code:



groups <- rep(1:2, each=2)
colMax <- function(x)apply(x, 2, max)
t(
    sapply(unique(groups), function(i)colMax(x[which(groups==i), ]))
)

      

Results:

     [,1] [,2] [,3]
[1,]    5    4   20
[2,]    7    8    9

      

+5


source


One long line:



t(sapply(seq(1,nrow(df1),by=2),function(i) apply(df1[seq(i,1+i),],2,max)))

      

+1


source


Another variant,

do.call(rbind, by(m, gl(nrow(m)/2, 2), function(x) apply(x, 2, max)))

      

+1


source


apply(mat, 2, function(x) tapply(x, # work on each column
       # create groups of 2 vector of proper length:  1,1,2,2,3,3,4,4 ....
      rep(1:(length(x)/2), each=2, len=length(x)) 
       max))

  [,1] [,2] [,3]
1    5    4   20
2    7    8    9

      

0


source







All Articles