Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of the column in data frame that contains the string as value

Tags:

dataframe

r

I have data frame like this :

df <- data.frame(col1 = c(letters[1:4],"a"),col2 = 1:5,col3 = letters[10:14])
 df
  col1 col2 col3
1    a    1    j
2    b    2    k
3    c    3    l
4    d    4    m
5    a    5    n

I want to find the index of the column of df that has values matching to string "a". i.e. it should give me 1 as result. I tried using which in sapply but its not working. Anybody knows how to do it without a loop ??

like image 285
user1021713 Avatar asked Oct 25 '12 05:10

user1021713


People also ask

How do you find the index of a value in a DataFrame?

Using index property The first option you have when it comes to accessing the index is pandas. DataFrame. index property returns the index (i.e. the row labels) of a pandas DataFrame.

How many indices are there in DataFrame?

But for now here's my answer: DataFrame is 2 dimensional, and its index are rows and columns (2 indexes) .


1 Answers

Something like this?

 which(apply(df, 2, function(x) any(grepl("a", x))))

The steps are:

  1. With apply go over each column
  2. Search if a is in this column with grepl
  3. Since we get a vector back, use any to get TRUE if any element has been matched to a
  4. Finally check which elements (columns) are TRUE (i.e. contain the searched letter a).
like image 55
johannes Avatar answered Oct 18 '22 20:10

johannes