開始使用免費開始

以 collectors 設定 col_types

設定匯入欄位型別的另一種方式是使用 collectors。你可以在 list() 中放入 collector 函式,並傳給 read_ 系列函式的 col_types 參數,以告訴它們該如何詮釋某欄位的值。

想看完整的 collector 函式列表,可以參考 collector 的文件。在本練習中你會用到兩個 collector 函式:

  • col_integer():此欄位要以整數來詮釋。
  • col_factor(levels, ordered = FALSE):此欄位要以具有 levels 的因子來詮釋。

本練習會使用 hotdogs.txtview),這是一個以定位字元分隔(tab-delimited)的檔案,第一列沒有欄位名稱。

本練習屬於課程

R 資料匯入入門

檢視課程

練習說明

  • 已為你建立未設定欄位型別的 hotdogs。請用 summary() 函式檢視其摘要。
  • 已為你定義兩個 collector 函式:facint。看一下它們,你能理解各自要收集什麼型別嗎?
  • 在第二個 read_tsv() 呼叫中,編輯 col_types 參數:傳入一個包含 facintintlist(),這樣第一欄會以因子匯入,第二與第三欄會以整數匯入。
  • hotdogs_factor 建立一個 summary()。將它與 hotdogs 的摘要比較。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import without col_types
hotdogs <- read_tsv("hotdogs.txt", col_names = c("type", "calories", "sodium"))

# Display the summary of hotdogs
___

# The collectors you will need to import the data
fac <- col_factor(levels = c("Beef", "Meat", "Poultry"))
int <- col_integer()

# Edit the col_types argument to import the data correctly: hotdogs_factor
hotdogs_factor <- read_tsv("hotdogs.txt",
                           col_names = c("type", "calories", "sodium"),
                           col_types = NULL)

# Display the summary of hotdogs_factor
___
編輯並執行程式碼