1

Say we have the following matrix,

x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))

What I'm trying to do is:

1- Find the maximum value of each row. For this part, I'm doing the following,

df <- apply(X=x, MARGIN=1, FUN=max)

2- Then, I want to extract the column names of the maximum values and put them next to the values. Following the reproducible example, it would be "C" for the three rows.

Any assistance would be wonderful.

1 Answers1

0

You can use apply like

maxColumnNames <- apply(x,1,function(row) colnames(x)[which.max(row)])

Since you have a numeric matrix, you can't add the names as an extra column (it would become converted to a character-matrix). You can choose a data.frame and do

resDf <- cbind(data.frame(x),data.frame(maxColumnNames = maxColumnNames))

resulting in

resDf
  A B C maxColumnNames
X 1 4 7              C
Y 2 5 8              C
Z 3 6 9              C
Jonas
  • 1,760
  • 1
  • 3
  • 12