Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve row and column name of particular cell in R

Tags:

dataframe

r

So if I have a data frame that looks like:

             A     B      C  
  rowname1   4.5   4      3.2
  rowname2   3     23     9

How do I get R to give me the name(s) of the row/columns that contain a particular number?

i.e. if I give the value 3, it gives back

 rowname2,A
like image 253
cianius Avatar asked Sep 17 '12 17:09

cianius


People also ask

How do I get the row name in R?

There is an inbuilt R function, row. names() which can be used to access the row names of the data frame, and successively it can be modified using the new vector list.

How do I get the name of a specific column in R?

To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in.

How do I reference a specific cell in R?

"R1C1" cell reference style For example, R1C1 refers to the cell A1. If you are in cell C1, the reference R[1]C[1] refers to the cell one column to the right and one row down, which is D2. The reference R1C refers to the cell in the first row and the same column as the cell containing the formula.

How can you retrieve the names of rows and columns of a data frame in R?

To find the column names and row names in an R data frame based on a condition, we can use row. names and colnames function.


2 Answers

Assuming no duplicates, you can use which combined 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 the actual row and column names of the location, then just index into them appropriately:

paste(rownames(df)[index[1]], colnames(df)[index[2]], sep=", ")
# [1] "1, X3"
like image 55
Andy Avatar answered Oct 11 '22 18:10

Andy


May be writing a simple function could help you out:

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="A     B      C  
  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 duplicated 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"
like image 34
Jilber Urbina Avatar answered Oct 11 '22 18:10

Jilber Urbina