2016-12-22 52 views
2

當我使用readr::read_csv讀取包含尾隨分隔符的CSV文件時,我收到一條警告,指出缺少一個列名稱。下面是一個簡短示例CSV文件的內容以重現此操作警告(存儲下面的片段在名爲example.csv文件):忽略readr中的尾部分隔符:: read_csv

A,B,C, 
2,1,1, 
14,22,5, 
9,-4,8, 
17,9,-3, 

注意後面的逗號在每一行的末尾。現在,如果我打開這個文件,

read_csv("example.csv") 

我得到以下警告:

Missing column names filled in: 'X4' 

即使我想與

read_csv("example.csv", col_types=cols_only(A=col_integer(), 
              B=col_integer(), 
              C=col_integer())) 

我仍然得到顯式地加載只有3列警告信息。

這是預期的行爲還是有一些方法可以告訴read_csv它應該忽略除指定的列之外的所有列?或者還有另一種方法來清理這個(顯然格式不正確的)CSV,以便尾隨分隔符被刪除/忽略?

+0

你可以添加一個小例子來說明問題嗎?警告是以某種方式影響輸出還是僅僅是一個信息? – aosmith

+0

這只是一個警告消息,但即使使用'cols_only',似乎所有列似乎都已導入,這似乎很奇怪。我編輯了我的問題以包含一個小例子CSV文件來顯示問題。 – cbrnr

回答

3

我不認爲你可以。從我可以在文檔中看到,cols_only()是您已經加載中的R對象

然而,從data.tablefread()功能可讓您選擇具體列名的文件中讀取:

DT <- fread("filename.csv", select = c("colA","colB"))

2

下面是錯誤消息的另一個示例。

> read_csv("1,2,3\n4,5,6", col_names = c("x", "y")) 
Warning: 2 parsing failures. 
row # A tibble: 2 x 5 col  row col expected actual   file expected <int> <chr>  <chr>  <chr>  <chr> actual 1  1 <NA> 2 columns 3 columns literal data file 2  2 <NA> 2 columns 3 columns literal data 

# A tibble: 2 x 2 
     x  y 
    <int> <int> 
1  1  2 
2  4  5 

這裏是修復/破解。另請參閱此SOF鏈接。 Suppress reader parse problems in r

> suppressWarnings(read_csv("1,2,3\n4,5,6", col_names = c("x", "y"))) 
# A tibble: 2 x 2 
     x  y 
    <int> <int> 
1  1  2 
2  4  5 
+0

這[博客文章](http://romainfrancois.blog.free.fr/index.php?post/2009/05/20/Disable-specific-warnings)介紹瞭如何只捕獲特定的警告。可以有用的只是抑制這個特定的警告。 – nevrome