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

前端 未结 2 1971
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  星月不相逢
    2020-12-16 01:38

    Since you mention you were trying to use sapply() but were unsuccessful, here's how you can do it:

    > sapply(df, function(x) any(x == "a"))
     col1  col2  col3 
     TRUE FALSE FALSE 
    > which(sapply(df, function(x) any(x == "a")))
     col1 
        1
    

    Of course, you can also use the grep()/grepl() approach if you prefer string matching. You can also wrap your which() function with unname() if you want just the column number.

提交回复
热议问题