列のクラス
colClasses 引数を使うと、読み込むファイルの各列に対してデータ型を指定できます。これにより、インポート処理の効率が上がり、列が正しいデータ型で読み込まれるようにできます。
colClasses 引数は次のように設定します。
read.delim("my_file.txt",
colClasses = c("character",
"numeric",
"logical"))
colClasses ベクトル内で列を "NULL" に設定すると、その列はスキップされ、データフレームには読み込まれません。
この演習はコースの一部です
Rでのデータインポート入門
演習の手順
hotdogsデータフレームは読み込み済みです。まずはhotdogsの構造を表示しましょう。- 2つ目の
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
___