给出数据框中对象的名称

Give colname of object in data frame

我确实有一个非常简单的问题,但找不到简单的解决方案(不知道为什么)

所以我想知道 r 如何让我知道对象在哪一列。 例如,如果我们采用 iris 数据集,我知道其中应该有 "setosa",但我希望命令 returns me the column-name ("Species").

谢谢:)

我们可以使用 sapply 遍历 list 检查是否有 any 'setosa' 并使用它来对列名称进行子集化

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

或使用select_if

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

如果有另一个条件只检查非数字列可能会更好

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

另一个基础 R 选项,诚然不比 快。

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"

这里有两个基本的 R 选项。

使用Filter

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

使用colSums

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