计算向量的最大版本

compute max version on a vector

我正在寻找矩阵每一行的最大包版本(即使用比较函数 compareVersion 而不是通常的 max)。我可以编写一个简单的递归循环,但我正在寻找更优雅的解决方案。我已经尝试 apply 但没有成功:

样本数据集:

M=matrix(c("2.7.5","1.7.3","1.7.8","0.9-7","0.9-5","0.10-7"), nrow = 2, ncol = 3, byrow = TRUE)

什么不起作用:

apply(M, 1, FUN = function(e1,e2) ifelse(compareVersion(e1,e2)==1, e1, e2))

是否可以避免对递归循环进行编码?

(也许首先在简单示例 x=c("2.7.5","1.7.3","1.7.8") 上,然后我可以轻松地将它应用于所有行)

使用多元版本mapply

mapply(function(e1,e2) ifelse(compareVersion(e1,e2)==1, e1, e2), e1=M[1,],e2=M[2,])

我发现的最好的方法是使用出色的函数 Reduce,它执行的正是我正在寻找的递归循环

Reduce uses a binary function to successively combine the elements of a given vector and a possibly given initial value.

矢量上的简单情况:

x = c("1.9-7","4.11-5",NA,"0.10-7")
Reduce(x=x, f=function(e1,e2) ifelse(compareVersion(e1,e2)==1, e1, e2), accumulate=FALSE)

在矩阵上:

M=matrix(c("2.7.5","1.7.3","1.7.8","0.9-7","0.9-5","0.10-7"), nrow = 2, ncol = 3, byrow = TRUE)
apply(M, 1, FUN = function(x) Reduce(x=x, f=function(e1,e2) ifelse(compareVersion(e1,e2)==1, e1, e2), accumulate=FALSE))