【发布时间】:2012-03-29 07:57:57
【问题描述】:
我想在每列中找到每 2 行的最大值(比如说)。如何在 R 中做到这一点?例如
matrix(c(3,1,20,5,4,12,6,2,9,7,8,7), byrow=T, ncol=3)
我想要这样的输出
matrix(c(5,4,20,7,8,9), byrow=T, ncol=3)
【问题讨论】:
我想在每列中找到每 2 行的最大值(比如说)。如何在 R 中做到这一点?例如
matrix(c(3,1,20,5,4,12,6,2,9,7,8,7), byrow=T, ncol=3)
我想要这样的输出
matrix(c(5,4,20,7,8,9), byrow=T, ncol=3)
【问题讨论】:
这是一种方法。
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), ]))
)
结果:
[,1] [,2] [,3]
[1,] 5 4 20
[2,] 7 8 9
【讨论】:
groups。但是 OP 对组定义的确切含义不是很清楚,所以我把它留给用户预先定义。
一条长线:
t(sapply(seq(1,nrow(df1),by=2),function(i) apply(df1[seq(i,1+i),],2,max)))
【讨论】:
另一种选择,
do.call(rbind, by(m, gl(nrow(m)/2, 2), function(x) apply(x, 2, max)))
【讨论】:
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
【讨论】: