1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RでのCSV読み込み

Posted at

RでCSVファイルを読み込む際には関数read.csvを用いる。標準で入っているため、ライブラリのインポートは必要ない。読み込むデータは作業ディレクトリに置いておくと、パスの記述が不要となるので楽。以下コードで作業ディレクトリの変更ができる。

workDir
setwd(dir = "C:/Users/user/Desktop/R")

以下コードでCSVファイルの読み込みができる。

readCsv.R
df <- read.csv("FileName")

ちなみにURLを指定することでWebから直接読み込むこともできる。以下の例はUCI Machine Learning RepositoryからWater Treatment Plant Data Setを読み込んでいる。

readCsvFromWeb.R
df <- read.csv(file="https://archive.ics.uci.edu/ml/machine-learning-databases/water-treatment/water-treatment.data")

またread.csvにはさまざまなオプションがある。実際に自分がCSVファイルを読み込む際には以下を実行した。

readCsvWithOption.R
df <- read.csv(file="Filename", header=FALSE, skip=2, na.strings=" ")
header
ヘッダ読み込みの有無(デフォルト:TRUE)
skip
読み込み時に指定行をスキップ
na.strings
指定した文字列をNAに変換

上記コードでは、" " の形式で空白が存在していたため、 na.strings=" " としている。Water Treatment Plant Data Set の場合は、? が入っているので、 na.strings="?" と指定する。ちなみに ?read.csv のように ? のあとに関数名を打つとヘルプを見ることができる。便利。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?