R:在每列的每两行中找到最大值 [英] R: finding maximum value every two rows in each column
本文介绍了R:在每列的每两行中找到最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想每2行(例如)在每一列中找到最大值.如何在R中做到这一点?例如
I want to find maximum value in each column for every 2 rows (say). How to do that in R? For example
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
重复数字序列. - 然后定义一个辅助函数来计算数组的列最大值-这是
max
的简单apply
. - 最后,将
sapply
与匿名函数一起使用,该匿名函数会将colMax
应用于每个分组的数组子集.
- Define a vector that contains information about the
groups
you want. In this case, I userep
to repeat a sequence of numbers. - Then define a helper function to calculate the column maximum of an array — this is a simple
apply
ofmax
. - finally, use
sapply
with an anonymous function that appliescolMax
to each of your grouped array subsets.
代码:
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
这篇关于R:在每列的每两行中找到最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文