Get row and column name of a specific cell in R

So, if I have a data frame that looks like this:

ABC rowname1 4.5 4 3.2 rowname2 3 23 9 

How do I get R to indicate the name (s) of a row / column that contain a specific number?

i.e. if I give a value of 3, it returns

  rowname2,A 
+4
source share
3 answers

If there are no duplicates, you can use which in conjunction with the arr.ind argument:

 df <- data.frame(matrix(sample(1:100,12), ncol=3)) # X1 X2 X3 # 1 84 58 36 # 2 9 40 92 # 3 100 28 78 # 4 15 98 29 index <- which(df==36, arr.ind=TRUE) # row col # [1,] 1 3 

If you must have actual row and column names for the location, then simply index them accordingly:

 paste(rownames(df)[index[1]], colnames(df)[index[2]], sep=", ") # [1] "1, X3" 
+14
source

Maybe writing a simple function can help you:

 Which.names <- function(DF, value){ ind <- which(DF==value, arr.ind=TRUE) paste(rownames(DF)[ind[1:nrow(ind)]], colnames(DF)[ind[2]], sep=', ') } DF <- read.table(text="ABC rowname1 4.5 4 3.2 rowname2 3 23 9", header=TRUE) Which.names(DF, value=3) [1] "rowname2, A" Which.names(DF, value=4.5) [1] "rowname1, A" Which.names(DF, value=9.0) [1] "rowname2, C" 

It also allows you to work with duplicate values.

  DF[1,1] <-3.0 Which.names(DF, value=3) [1] "rowname1, B" "rowname2, B" DF[1,2] <- 3 Which.names(DF, value=3) [1] "rowname1, B" "rowname2, B" "rowname1, B" 
+4
source

there are some problems in the code in response to Jilber, you need to change a bit, it should be like this (R version 3.1.2):

both works (note the difference between the initial letters of these two functions: "W" and "w")

first

 Which.names <- function(DF, value){ ind <- which(DF==value, arr.ind=TRUE) for (i in 1:nrow(ind)) print(paste(rownames(DF)[ind[i,"row"]], colnames(DF)[ind[i,"col"]], sep=', ')) } 

2nd (best)

 which.names <- function(DF, value){ ind <- which(DF==value, arr.ind=TRUE) print(paste(rownames(DF)[ind[,"row"]], colnames(DF)[ind[,"col"]], sep=', ')) } 

result below

 > DF <- read.table(text="ABC + rowname1 4.5 4 3.2 + rowname2 3 23 9", header=TRUE) > DF ABC rowname1 4.5 4 3.2 rowname2 3.0 23 9.0 > Which.names(DF,3) [1] "rowname2, A" > which.names(DF,3) [1] "rowname2, A" > Which.names(DF,4) [1] "rowname1, B" > which.names(DF,4) [1] "rowname1, B" > Which.names(DF,9) [1] "rowname2, C" > which.names(DF,9) [1] "rowname2, C" > DF[1,1] <-3.0 > DF ABC rowname1 3 4 3.2 rowname2 3 23 9.0 > Which.names(DF,3) [1] "rowname1, A" [1] "rowname2, A" > which.names(DF,3) [1] "rowname1, A" "rowname2, A" > DF[1,2] <- 3 > DF ABC rowname1 3 3 3.2 rowname2 3 23 9.0 > Which.names(DF,3) [1] "rowname1, A" [1] "rowname2, A" [1] "rowname1, B" > which.names(DF,3) [1] "rowname1, A" "rowname2, A" "rowname1, B" 
0
source

Source: https://habr.com/ru/post/1434673/


All Articles