I have a matrix from which I would like to select an observation together with its column name.
If I use subset() or matrix[]%in% then I get the whole row.
I would only like to get that single observation and its column name.
Is there a way to do this?
Here’s an example:
matrix:
col1 col2 col3
row 1 10 20 30
row 2 30 30 40
Now I would like to select the value and column name with the highest value:
max <- max(matrix)
subset(matrix, matrix==max)
This gives the output:
col1 col2 col3
row 2 30 30 40
However what I would like to get is:
col3
40
As you already know the value, you just need to get the column names.
Calling your matrix
mfor the obvious reason:To see which columns contain the max (or any particular value), and their names,
applycan be used to return a logical vector with names:whichtells you which values are true:And just the names, if that is what you need: