查找数据帧中是否存在列


110

我有一个名为“ abcframe”的data.frame

     a  b  c
     1  1  1
     2  2  3

如何查找给定数据框中是否存在列?例如,我想查找data.frame abcframe中是否存在列d


1
您是否想知道数据框是否具有名称为的列d,还是想知道给定的矢量是否d等于数据框的列之一?

我想知道数据框是否具有名称为d的色块
Sunny Sunny

祝您有100票阳光明媚的晴天!:-)
TMS

Answers:


196

假设数据框的dat名称为"d",要检查的列名称为,则可以使用%in%运算符:

if("d" %in% colnames(dat))
{
  cat("Yep, it's in there!\n");
}

6
如果您正在寻找反数,即如果该列不存在,则只需!在开头添加:if(!"d"%in% colnames(dat))
toto_tico

很棒的答案。如果要查找列“ d”,“ e”和“ f”,该如何扩展?会是:if("d" & "e" & "f" %in% colnames(dat)) { cat("Yep, it's in there!\n"); }。谢谢!-哦,我可能已经找到了自己的答案:stackoverflow.com/questions/21770912/...
桑德·W·范德兰

6
all(c(“ d”,“ e”,“ f”)%in%colnames(dat))
skan

24

您有多种选择,包括使用%in%grepl

dat <- data.frame(a=1:2, b=2:3, c=4:5)
dat
  a b c
1 1 2 4
2 2 3 5

要获取列名:

names(dat)
[1] "a" "b" "c"

使用%in%检查成员:

"d" %in% names(dat)
[1] FALSE

Or use `grepl` to check for a match:

grepl("d", names(dat))
[1] FALSE FALSE FALSE

11
为了grepl更精确一点,您可以使用grepl("^d$",names(dat)),以确保dd不会返回名称为name的列TRUE
BenBarnes 2012年

谢谢你,colnames对我没用,但是对我names有用。
Docconcoct

@Andrie有一种方法可以将列与两个大型数据框进行比较,以查看另一列中缺少哪些列名?
sar


2

您也可以if(!is.null(abcframe$d))用来测试中是否d存在abcframe

dat <- data.frame(a = 1:2, b = 2:3, c = 4:5)

if (!is.null(dat$d)) {
  print("d exists")
} else {
  print("d does not exist")
}
if (!is.null(dat$a)) {
  print("a exists")
} else {
  print("a does not exist")
}

2
有趣的是,此操作会因tidyverse滴答声而失败,因为'dat $ d'将发出警告。
miratrix
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.