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

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 to share