Give colname of object in data frame

Viewed 30

i do have a very easy question, but can't find an easy solution (dunno why)

So I would like to know how r could let me know in what column an object is. e.g if we take the iris dataset I know there should be "setosa" somewhere in it, but I would like that the command returns me the column-name ("Species").

Thank you :)

3 Answers

We can use sapply to loop over the list check if there are any 'setosa' and use that to subset the column names

names(iris)[sapply(iris, function(x) any(x == 'setosa'))]
#[1] "Species"

Or using select_if

library(dplyr)
iris %>% 
     select_if(~ any(. == 'setosa')) %>%
     names
#[1] "Species"

It may be better to have another condition to check only non-numeric columns

iris %>%
     select_if(~ is.factor(.) && any(. == 'setosa')) %>%
     names

Another base R option, admittedly no faster than @akrun's answer.

sapply(iris, function(x) 'setosa' %in% x)
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#        FALSE        FALSE        FALSE        FALSE         TRUE 

names(iris)[sapply(iris, function(x) 'setosa' %in% x)]
# [1] "Species"

Here are two base R options.

Using Filter :

names(Filter(function(x) any(x == 'setosa'), iris))
#[1] "Species"

Using colSums :

names(iris)[colSums(iris == 'setosa') > 0]
#[1] "Species"
Related