2014-10-29 41 views
2

我正在使用data.table的fread函數將csvfile加載到R中。它有一堆我不需要的列,所以select參數派上用場。不過,我注意到,如果select中指定的列中有一列不存在於csv文件中,fread將默默繼續。如果csvfile中不存在其中一個選定的列,是否有可能使R發生錯誤?fread(data.table)選擇列,如果列未找到,則拋出錯誤

#csvfile has "col1" "col2" "col3" "col4" etc 

colsToKeep <- c("col1", "col2" "missing") 

data <- fread(csvfile, header=TRUE, select=colsToKeep, verbose=TRUE) 

在上述例子中,data將有兩列:col1col2。剩餘的列將按預期丟棄,但默認跳過missing。如果知道fread跳過該列,肯定會很高興,因爲它沒有找到它。

回答

4

我建議先解析第一行,然後拋出自己的錯誤。你可以這樣做:

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")) 
+1

什麼是'%chin%'? – stephentgrammer 2014-10-29 23:27:33

+2

它是'data.table'的快速版本,用於字符向量的'%in%'。 '''?%下巴%'''' – shadowtalker 2014-10-30 00:03:19