我想在每列中找到每2行的最大值(比方说).如何在R中做到这一点?例如
matrix(c(3,1,20,5,4,12,6,2,9,7,8,7), byrow=T, ncol=3)
Run Code Online (Sandbox Code Playgroud)
我希望输出像这样
matrix(c(5,4,20,7,8,9), byrow=T, ncol=3)
Run Code Online (Sandbox Code Playgroud)
这是一种做法.
groups.在这种情况下,我rep用来重复一系列数字.apply的max.sapply适用colMax于每个分组数组子集的匿名函数.代码:
groups <- rep(1:2, each=2)
colMax <- function(x)apply(x, 2, max)
t(
sapply(unique(groups), function(i)colMax(x[which(groups==i), ]))
)
Run Code Online (Sandbox Code Playgroud)
结果:
[,1] [,2] [,3]
[1,] 5 4 20
[2,] 7 8 9
Run Code Online (Sandbox Code Playgroud)