Ahmed Salhin - 3 months ago 18

R Question

I have the following numeric vectors

`x`

`y`

`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

`pmax`

`a b c`

`d b f`

2 2 4

Answer

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 `cbind`

ing 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
```