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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With