LoginSignup
0
0

More than 1 year has passed since last update.

【R】データの読み込み

Last updated at Posted at 2019-01-24

Rを久々に使うと、特にデータファイルの読み込みの仕方を忘れていることが多いので、備忘録としてまとめてみました。

小規模なデータの取り扱い

ベクトルの作成

  • 同じデータ型の複数のデータを扱う時は、c関数を使ってベクトルを作成します。
Rのコンソール
> height <- c(35, 30, 21, 18, 28, 10)
> height
[1] 35 30 21 18 28 10

中~大規模なデータの取り扱い

ベクトルから行列を作成

  • cbind関数を使うことで、複数のベクトルを1つの行列にまとめることができます。
  • 行列は「全ての列が同じデータ型であること」という条件があるため、数値と文字列を混在させることができず、解析にはやや使いづらいデータかもしれません。
Rのコンソール
> height <- c(35, 30, 21, 18, 28, 10)
> leaves <- c(10, 6, 7, 8, 7, 4)
> flowers <- c(15, 5, 2, 0, 3, 0)
> orchids <- cbind(Height=height, Leaves=leaves, Flowers=flowers)
> orchids
     Height Leaves Flowers
[1,]     35     10      15
[2,]     30      6       5
[3,]     21      7       2
[4,]     18      8       0
[5,]     28      7       3
[6,]     10      4       0
  • data.frame関数で行列データを読み込むと、行列をデータフレームに変換できます。
Rのコンソール
> df_orchids <- data.frame(orchids)
> df_orchids
  Height Leaves Flowers
1     35     10      15
2     30      6       5
3     21      7       2
4     18      8       0
5     28      7       3
6     10      4       0

ベクトルからデータフレームを作成

  • data.frame関数を使うことで、複数のベクトルを1つのデータフレームにまとめることができます。
Rのコンソール
> height <- c(35, 30, 21, 18, 28, 10)
> leaves <- c(10, 6, 7, 8, 7, 4)
> flowers <- c(15, 5, 2, 0, 3, 0)
> orchids <- data.frame(Height=height, Leaves=leaves, Flowers=flowers)
> orchids
  Height Leaves Flowers
1     35     10      15
2     30      6       5
3     21      7       2
4     18      8       0
5     28      7       3
6     10      4       0
  • データフレームとしてデータを保持しておけば、"データフレーム名$列名"の形で任意の列のデータを取り出すことができます。
Rのコンソール
> orchids$Leaves
[1] 10  6  7  8  7  4

CSVファイルからデータフレームを作成

  • CSVなどのデータファイルからデータを読み込む場合、read.table関数を使ってデータフレームとして取り込みます。
    • "header"で「ヘッダ行の有無」を指定します。
    • "row.names"で「指定した列番号のデータを行名として扱う」ことができます。
    • データファイルに日本語文字が含まれている場合などは、"encoding"で「文字コード」を指定します。
    • "sep"で「区切り文字」を指定します。
  • Windows環境の場合、ファイルパスの区切り文字が「バックスラッシュ2つ」になるので要注意。
orchids.csv
,Height,Leaves,Flowers
orchid1,35,10,15
orchid2,30,6,5
orchid3,21,7,2
orchid4,18,8,0
orchid5,28,7,3
orchid6,10,4,0
Rのコンソール
> orchids <- read.table("C:\\orchids.csv", header=TRUE, row.names=1, encoding="CP932", sep=",")
> orchids
        Height Leaves Flowers
orchid1     35     10      15
orchid2     30      6       5
orchid3     21      7       2
orchid4     18      8       0
orchid5     28      7       3
orchid6     10      4       0
0
0
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
0
0