Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compute max version on a vector

Tags:

r

max

apply

I am looking for the maximum package version (ie using comparison function compareVersion instead of the usual max) on each row of a matrix. I could code a simple recursive loop but I am looking for a more elegant solution. I have tried apply with no success:

sample data set:

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)

what doesn't work:

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

is it possible to avoid coding the recursive loop?

(Maybe first on the simple example x=c("2.7.5","1.7.3","1.7.8"), then I can easily apply it on all rows)

like image 537
RockScience Avatar asked Dec 06 '25 21:12

RockScience


1 Answers

The best I have found is using the excellent function Reduce, which is doing exactly the recursive loop I was looking for

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

The simple case on a vector:

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)

On the matrix:

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))
like image 86
RockScience Avatar answered Dec 09 '25 11:12

RockScience