Ahmed Salhin Ahmed Salhin - 8 months ago 34
R Question

Return attributes of pmax function output

I have the following numeric vectors


x <- c(a=1,b=2,c=3)
y <- c(d=2,e=1,f=4)

I want to find the parallel maximum of each elements in the vectors, so I used:

> pmax(x,y)
a b c
2 2 4

The output has the right values, however, it returns the wrong names. The documentation for
mentions that it returns the attributes of the first argument, hence the
a b c
. Is there a way of getting the names of the maximum values? The desired output is as follow:

d b f
2 2 4


One option would be using max.col for finding the index of the maximum value per each row. For that, we need to create a matrix/data.frame by cbinding the vectors ('xy') and its names ('nmxy'). Create a row/column index ('ij') and subset the elements of 'xy' and set the names from 'nmxy'.

xy <- cbind(x,y)
nmxy <- cbind(names(x), names(y))
ij <- cbind(1:nrow(xy), max.col(xy))
setNames(xy[ij], nmxy[ij])
#  d b f 
#  2 2 4