首页 > 解决方案 > 在数据框中包含必填列

问题描述

我在下面有一个数据框。

asd <- data.frame(a=c(1:10),b=c(11,20),c=(21:30),d=c(31:40),e=c(41,50),f=c(51,60))

以下是包含 asd 列名的 2 个向量

Column_list1 <- c("a","b","d")
Column_list2 <- c("c","e","f")

以下是列的强制列表

mandatory_column <- c("a","b","d","e")

现在实际上我的问题是当我尝试运行asd[Column_list1]时,结果应该抛出一条消息。因为必填列应该是c("a","b","d","e")并且因为Column_list1没有“e”,所以我需要打印消息“请同时包含列“e””。这有可能实现吗?

预期产出

asd[Column_list1]
Please include column "e" as well
asd[mandatory_column]
    a  b  d  e
1   1 11 31 41
2   2 20 32 50
3   3 11 33 41
4   4 20 34 50
5   5 11 35 41
6   6 20 36 50
7   7 11 37 41
8   8 20 38 50
9   9 11 39 41
10 10 20 40 50

标签: r

解决方案


如果你想弄乱你的 object 的类,asd就会想到 S3 方法。

`[.special` <- function(x, i, ..., mandatory = mandatory_column){
  on.exit({
    cols_missing <- setdiff(mandatory, i)
    if(length(cols_missing) > 0){
      msg <- paste(sQuote(cols_missing), collapse = ", ")
      msg <- paste("Please include columns", msg)
      warning(msg)
    }
  })
  NextMethod(x, i, ...)
}


Column_list1 <- c("a","b","d")
Column_list2 <- c("c","e","f")
mandatory_column <- c("a","b","d","e")

第一次调用仍然调用该[.data.frame方法。

asd[Column_list1]

现在调用该[.special方法。它对数据进行子集化并给出警告。

class(asd) <- c("special", class(asd))
asd[Column_list1]
asd[Column_list2]
asd[mandatory_column]

推荐阅读