1 Introduction

We can organize our data without using any special packages, but there’s also an option to install and use packages, called “tidyverse”, from the web that are specifically designed for data organization.

This page demonstrate both methods step by step, but in class, we’ll only practice the method that doesn’t use any packages.

データ整備は特別なパッケージを使わずに行うことができるが,データ整備に特化したパッケージ(「tidyverse」という名前)をインターネット上からインストールして使用することもできる.

このページでは2つの方法を順に示すが,授業ではパッケージを使わない方法のみを演習する.

2 Organizing without packages

2.1 Create “data frame” object

Let’s copy and paste the chunk below into your R console.

下のチャンクを皆さんのRのコンソールにコピーアンドペーストしよう.

beatles <- data.frame(
  name = c("John", "Paul", "George", "Ringo"), 
  born = c(1940, 1942, 1943, 1940),
  decease = c(1980, NA, NA, NA), 
  height = c(179, 180, 178, 170)
  )
beatles
##     name born decease height
## 1   John 1940    1980    179
## 2   Paul 1942      NA    180
## 3 George 1943      NA    178
## 4  Ringo 1940      NA    170

2.2 Extracting rows or columns

We can specify the conditions for the rows (observations) we want to keep using brackets [ ]. The brackets are used in the format [row selection, column selection]. If no specific rows or columns are specified, all elements will be extracted.

For example, to extract the first row, we would specify the row number.

残す行(observation)の条件をブラケット [ ] を使って指定する. ブラケットは [抽出する行の指定, 抽出する列の指定] の形式で使う. 指定がなければすべての要素が抽出される.

たとえば,1行目を抽出するには次のように行番号を指定する.

beatles[1, ]
##   name born decease height
## 1 John 1940    1980    179

To extract the first column, specify the column number like this.

1列目を抽出するには次のように列番号を指定する.

beatles[, 1]
## [1] "John"   "Paul"   "George" "Ringo"

We can also extract data by specifying the column names (variable names).

列の名前(変数名)を指定して抽出することもできる.

beatles$born
## [1] 1940 1942 1943 1940
beatles[, "born"]  # same as above 
## [1] 1940 1942 1943 1940

We can also specify which rows to extract based on the attributes of a particular column.

ある列の属性を利用して抽出する行を指定することもできる.

beatles[beatles$born == 1940, ]
##    name born decease height
## 1  John 1940    1980    179
## 4 Ringo 1940      NA    170

The above is implemented by specifying whether to extract or not with TRUE/FALSE. Let’s confirm this with the following steps.

上は,抽出するかどうかを TRUE/FALSE で指定することによって実装されている. このことを以下のように確認しよう.

beatles$born == 1940
## [1]  TRUE FALSE FALSE  TRUE
beatles[c(TRUE, FALSE, FALSE, TRUE), ]
##    name born decease height
## 1  John 1940    1980    179
## 4 Ringo 1940      NA    170

To assign a dataset with selected elements to a new object, use <- (we can also overwrite an existing object with it).

一部の要素を抽出したデータセットを新しいオブジェクトに割り当てるには <- を用いる(既に存在するオブジェクトに上書きすることも可能).

beatles_ver2 <- beatles[beatles$born == 1940, ]
beatles_ver2
##    name born decease height
## 1  John 1940    1980    179
## 4 Ringo 1940      NA    170

We can also specify multiple conditions.

複数の条件を指定することもできる.

beatles[beatles$born == 1940 & beatles$height < 175, ]
##    name born decease height
## 4 Ringo 1940      NA    170

2.3 Changing the value of the elements

George Harrison passed away in 2001.

ジョージ・ハリスンは2001年に亡くなっている.

beatles$decease[beatles$name == "George"] <- 2001
beatles[beatles$name == "George", "decease"] <- 2001  # same as above 
beatles
##     name born decease height
## 1   John 1940    1980    179
## 2   Paul 1942      NA    180
## 3 George 1943    2001    178
## 4  Ringo 1940      NA    170

2.4 Creating new variables

beatles_ver3 <- beatles
beatles_ver3$primary_role <- c("vocal", "vocal", "guitar", "drum")
beatles_ver3
##     name born decease height primary_role
## 1   John 1940    1980    179        vocal
## 2   Paul 1942      NA    180        vocal
## 3 George 1943    2001    178       guitar
## 4  Ringo 1940      NA    170         drum

2.5 Merging two datasets

Let’s merge the following two datasets:

  • beatles … name, born, decease, height
  • beatles_primary_role … name, primary_role

We specify the key variable, name, for merging with the key argument in the merge function.

マージには merge 関数を使い,by 引数でマージするためのキー変数「name」を指定する.

beatles_primary_role <- data.frame(
  name = c("John", "Paul", "George", "Ringo"), 
  primary_role = c("vocal", "vocal", "guitar", "drum")
  )
beatles_primary_role
##     name primary_role
## 1   John        vocal
## 2   Paul        vocal
## 3 George       guitar
## 4  Ringo         drum
merge(beatles, beatles_primary_role, by = "name")
##     name born decease height primary_role
## 1 George 1943    2001    178       guitar
## 2   John 1940    1980    179        vocal
## 3   Paul 1942      NA    180        vocal
## 4  Ringo 1940      NA    170         drum

3 Organizing with Packages

3.1 Packages in R

R comes with a wide variety of function collections called ‘packages.’ If you want to use a package that isn’t installed by default when you install R, you’ll need to manually download and install it from the internet.

パッケージには大別すると次の3種類がある:

  1. Rをインストールした時に自動的にインストールされており,Rを起動したときにデフォルトで使えるように設定されているもの(base::c, utils::str, etc.)
  2. Rをインストールした時に自動的にインストールされているが,Rを起動したときにデフォルトでは読み込まれていないもの(MASS::Boston, Matrix::Cholesky, etc.)
    • library(パッケージ名) で読み込んで 関数名 で呼び出すか,パッケージを読み込まずに パッケージ名::関数名 で呼び出す
  3. ユーザーが自分でインストールしなければ使えないもの(tidyverse, data.table, etc.)
    • install.packages("パッケージ名") でインストールし(最初の一度だけ実行),library(パッケージ名) で読み込む(Rを起動する度に実行)
    • Rstudio で install.packages が使えない場合,PC がインターネットに接続されていることを確認したうえで,CRAN レポジトリを変更してリトライ:Tools > Global Options > Packages > Primary CRAN repository を 「Japan (Tokyo)」 などに変更(参考:Setting CRAN repository options

補足:同じ名前の関数が複数のパッケージで使用されている場合があるので,常に パッケージ名::関数名 の形式でパッケージを指定するのを好む人もいる.

3.2 tidyverse package

A common approach to organizing and manipulating data is to use functions from the tidyverse package.

データの整理・操作は tidyverse というパッケージに含まれる関数を使うのが一般的.

  • 正確には,tidyversedplyr (読み方:“dee-ply-er”) や ggplot2 などの複数のパッケージを束ねたもの
  • tidyverse をインストール/ロードすれば dplyrggplot2 などが同時にインストール/ロードされる

3.2.1 Installing the package

Install the package just once after installing R.

パッケージのインストールは R のインストール後に一度だけ実行する.

install.packages("tidyverse")  # run for the first time only

3.2.2 Loading the package

After installation, load the package in R. Unlike installing the package, this step needs to be done each time you start R (or RStudio).

インストール後に R にパッケージを読み込む. こちらはパッケージのインストールと異なり,R (または RStudio)を起動するたびに実行する.

library(tidyverse)

The dplyr (pronounced “dee-ply-er”) package included here is used for handling data.

この中に含まれる dplyr はデータのハンドリングを行うパッケージ.

  • filter … fetch only the subset (rows) we’re interested in
  • select … select one or multiple columns (variables)
  • mutate … creates new columns (variables)
  • rename … change columns (variables) name
  • left_join … join (merge) two datasets
  • summarise … summarize data
  • group_by … group the rows
    • Note: group_by alone will not give any output; it should be followed by summarise (or mutate) function.
  • filter … 条件に合致する行を抽出
  • select … 条件に合致する列(変数)を抽出
  • mutate … 新しい列(変数)を作成
  • rename … 列(変数)の名前を変更
  • left_join … 2つのデータセットを統合
  • summarise … データを要約
  • group_by … 行をグルーピング
    • Note: group_by はそれ単体で使われるわけではなく,通常は summarise 関数と併用される

3.3 Example of The Beatles data frame: Create “tibble” object

We can create a slightly more user-friendly data frame using the tibble::tibble function, compared to the data.frame objects made with data.frame function.

data.frame で作成したデータフレームのオブジェクトよりも少し扱いやすいデータフレーム型オブジェクトを tibble::tibble 関数で作成できる.

beatles <- tibble::tibble(
  name = c("John", "Paul", "George", "Ringo"), 
  born = c(1940, 1942, 1943, 1940),
  decease = c(1980, NA, NA, NA), 
  height = c(179, 180, 178, 170)
  )
beatles
## # A tibble: 4 × 4
##   name    born decease height
##   <chr>  <dbl>   <dbl>  <dbl>
## 1 John    1940    1980    179
## 2 Paul    1942      NA    180
## 3 George  1943      NA    178
## 4 Ringo   1940      NA    170

3.4 filter

Specify the conditions for the rows (observations) to keep.

残す行(observation)の条件を指定する.

beatles %>% filter(born >= 1941)
## # A tibble: 2 × 4
##   name    born decease height
##   <chr>  <dbl>   <dbl>  <dbl>
## 1 Paul    1942      NA    180
## 2 George  1943      NA    178

To assign the dataset after applying the filter, use <- to create a new object.

filter を適用した後のデータセットを新しいオブジェクトに割り当てるには <- を用いる(上書きも可).

beatles_ver2 <- beatles %>% filter(born >= 1941)
beatles_ver2
## # A tibble: 2 × 4
##   name    born decease height
##   <chr>  <dbl>   <dbl>  <dbl>
## 1 Paul    1942      NA    180
## 2 George  1943      NA    178

We can also specify multiple conditions.

複数の条件を指定することもできる.

beatles %>% filter(born >= 1941 & height < 180)
## # A tibble: 1 × 4
##   name    born decease height
##   <chr>  <dbl>   <dbl>  <dbl>
## 1 George  1943      NA    178

3.5 select

Specify the names of the columns (variables) we want to keep.

残す列(変数)の名前を指定する.

beatles %>% select(name)
## # A tibble: 4 × 1
##   name  
##   <chr> 
## 1 John  
## 2 Paul  
## 3 George
## 4 Ringo

3.6 mutate

Create a new column (variable).

新しく列(変数)を作成する.

beatles %>% mutate(primary_role = c("vocal", "vocal", "guitar", "drum"))
## # A tibble: 4 × 5
##   name    born decease height primary_role
##   <chr>  <dbl>   <dbl>  <dbl> <chr>       
## 1 John    1940    1980    179 vocal       
## 2 Paul    1942      NA    180 vocal       
## 3 George  1943      NA    178 guitar      
## 4 Ringo   1940      NA    170 drum

3.7 rename

Rename the columns (variables).

列(変数)の名前を変える.

beatles %>% rename(birth_year = born)
## # A tibble: 4 × 4
##   name   birth_year decease height
##   <chr>       <dbl>   <dbl>  <dbl>
## 1 John         1940    1980    179
## 2 Paul         1942      NA    180
## 3 George       1943      NA    178
## 4 Ringo        1940      NA    170

3.8 left_join

Merge with another dataset.

別のデータセットと統合する.

beatles_primary_role <- tibble::tibble(name = c("John", "Paul", "George", "Ringo"), 
                                       primary_role = c("vocal", "vocal", "guitar", "drum"))
beatles_primary_role
## # A tibble: 4 × 2
##   name   primary_role
##   <chr>  <chr>       
## 1 John   vocal       
## 2 Paul   vocal       
## 3 George guitar      
## 4 Ringo  drum
beatles %>% left_join(beatles_primary_role, by = "name")
## # A tibble: 4 × 5
##   name    born decease height primary_role
##   <chr>  <dbl>   <dbl>  <dbl> <chr>       
## 1 John    1940    1980    179 vocal       
## 2 Paul    1942      NA    180 vocal       
## 3 George  1943      NA    178 guitar      
## 4 Ringo   1940      NA    170 drum

3.9 summarise

Summarize the data.

データを要約する.

beatles %>% summarise(mean_height = mean(height), 
                      std_dev_height = sd(height),
                      sample_size = n())
## # A tibble: 1 × 3
##   mean_height std_dev_height sample_size
##         <dbl>          <dbl>       <int>
## 1        177.           4.57           4

3.10 group_by

We can use the summarise function to calculate summary statistics or perform other statistical operations for each group.

summarise 関数と組み合わせて使うことで,グループごとの要約統計量を計算したり何らかの統計処理を行うことができる.

beatles %>% 
  group_by(born) %>% 
  summarise(mean_height = mean(height), 
            std_dev_height = sd(height),
            sample_size = n())
## # A tibble: 3 × 4
##    born mean_height std_dev_height sample_size
##   <dbl>       <dbl>          <dbl>       <int>
## 1  1940        174.           6.36           2
## 2  1942        180           NA              1
## 3  1943        178           NA              1