我正在使用data.table的fread函数将csvfile加载到R中.它有一堆我不需要的列,所以select参数派上用场.但是,我注意到,如果在csvfile中不存在select中指定的列之一,则fread将以静默方式继续.如果csvfile中不存在所选列之一,是否可以使R抛出错误?
#csvfile has "col1" "col2" "col3" "col4" etc
colsToKeep <- c("col1", "col2" "missing")
data <- fread(csvfile, header=TRUE, select=colsToKeep, verbose=TRUE)
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,data将有两列:col1,col2.其余列将按预期删除,但会missing被静默跳过.如果知道fread正在跳过该列,那肯定会很好,因为它没有找到它.
我建议先抢先解析第一行,然后抛出你自己的错误.你可以这样做:
read_cols <- function(file_name, colsToKeep) {
header <- fread(file_name, nrows = 1, header = FALSE)
all_in_header <- all(colsToKeep %chin% unlist(header))
stopifnot(all_in_header)
fread(file_name, header=TRUE, select=colsToKeep, verbose=TRUE)
}
my_data <- read_cols(csvfile, c("col1", "col2" "missing"))
Run Code Online (Sandbox Code Playgroud)