Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row and column name of data.frame according to condition in R

Tags:

r

This is probably much easier than I am making it. It is one of those little problems which hangs you up and you wonder why.

Given dataframe as so:

a <- c(1,2,3)
b <- c(4,5,6)
test.df <- data.frame(a,b)

How could one use iterate through the values in each column and return the column name and row name if the value = '1'?

Something like this:

for (i in test.df) {
    for (j in i) {
        if (i == 1) {
            print(rowname,columnname)
            }
        }
    }  
}  

Where rowname and columnname are actual values.

like image 578
branch.lizard Avatar asked Jan 30 '15 20:01

branch.lizard


People also ask

How do I get the row name from a DataFrame in R?

Method 1 : using rownames() A data frame's rows can be accessed using rownames() method in the R programming language. We can specify the new row names using a vector of numerical or strings and assign it back to the rownames() method.

How do I get column names from a DataFrame 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. This operation will then return the column you want as a vector.


3 Answers

Using which and arr.ind=T is a way:

Example Data

a <- c(1,2,3)
b <- c(4,5,6)
test.df <- data.frame(a,b)

Solution and Output

#test.df==1 gives a TRUE/FALSE matrix
#which with the arr.ind argument=TRUE gives the row/col of the TRUE elements
a <- which(test.df==1,arr.ind=T)

> a
     row col
[1,]   1   1

And then you use the above to get the row and column names:

> row.names(test.df[a[,1],] ) #row names
[1] "1"

> names(test.df[a[,2]])       #column names
[1] "a"
like image 127
LyzandeR Avatar answered Nov 14 '22 21:11

LyzandeR


Another approach:

> col = colnames(test.df)[apply(test.df, 2, function(u) any(u==1))]
> col
[1] "a"
> row = row.names(test.df)[apply(test.df, 1, function(u) any(u==1))]
> row
[1] "1"
like image 38
Colonel Beauvel Avatar answered Nov 14 '22 22:11

Colonel Beauvel


This is an old thread but I am not very satisfied with the previous solutions.

For me the most intuitive is:

row.names(data)[which(data$feature1==value)]

Which is basically saying: Given the row names of all the data give me those where a given condition is satisfied.

like image 26
Luis Chaves Rodriguez Avatar answered Nov 14 '22 21:11

Luis Chaves Rodriguez