Get the column name and row name of a specific value in a dataframe

Viewed 1373

Let's say I have this dataframe:

> df <- data.frame(a=c(1, 2, 3), b=c(4, 5, 6), c=c(7, 8, 9), row.names=c(100, 200, 300))
> df
    a b c
100 1 4 7
200 2 5 8
300 3 6 9
> 

And I want to get the row name and index name of the occurrence of 5 in this dataframe. I could do:

> paste("row:", rownames(df)[rowSums(df == 5) > 0], "column:", colnames(df)[colSums(df == 5) > 0], collapse=" ")
[1] "row: 200 column: b"
> 

But I assume there is a better way.

My desired output is:

row: 200 column: b

Since 5 is located there.

Is there a better way to do this?

2 Answers

You may use which with arr.ind = TRUE to get row and column number where 5 is present. This can be changed to row and column names.

mat <- which(df == 5, arr.ind = TRUE)
paste('row : ', rownames(df)[mat[, 1]], 'column :', colnames(df)[mat[, 2]])
#[1] "row :  200 column : b"      

Using melt from reshape2

library(reshape2)
with(melt(df == 5), sprintf('row : %s column: %s', Var1[value], Var2[value] ))
[1] "row : 200 column: b"
Related