我正在使用data.table的fread
函数将csvfile加载到R中。它有一堆我不需要的列,因此select
参数派上了用场。但是,我注意到,如果在select中指定的列之一在csvfile中不存在,则fread会继续静默运行。如果csvfile中不存在所选列之一,是否有可能使R引发错误?
#csvfile has "col1" "col2" "col3" "col4" etc
colsToKeep <- c("col1", "col2" "missing")
data <- fread(csvfile, header=TRUE, select=colsToKeep, verbose=TRUE)
在上面的示例中,
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"))
关于r - fread(data.table)选择列,如果未找到列则抛出错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26641945/