欄位類別
colClasses 參數可讓你為所讀取檔案的每個欄位指定資料型別。這能提升匯入的效率,並確保各欄位以正確的資料型別讀入。
你可以透過設定 colClasses 參數來達成:
read.delim("my_file.txt",
colClasses = c("character",
"numeric",
"logical"))
如果在 colClasses 向量中將某個欄位設為 "NULL",該欄位會被略過,不會載入到資料框中。
本練習屬於課程
R 資料匯入入門
練習說明
- 已載入
hotdogs資料框。請先顯示hotdogs的結構。 - 在第二個
read.delim()呼叫的colClasses參數中,將第 1、2、3 欄依序設為 'character'、'NULL'、'numeric'。 - 顯示
hotdogs2的結構,看看有什麼不同。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Previous call to import hotdogs.txt
hotdogs <- read.delim("hotdogs.txt", header = FALSE, col.names = c("type", "calories", "sodium"))
# Display structure of hotdogs
___
# Edit the colClasses argument to import the data correctly: hotdogs2
hotdogs2 <- read.delim("hotdogs.txt", header = FALSE,
col.names = c("type", "calories", "sodium"),
colClasses = c(___, ___, ___))
# Display structure of hotdogs2
___