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

前端 未结 2 1968
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 01:10

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条回答
  •  Happy的楠姐
    2020-12-16 01:48

    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).

提交回复
热议问题