1 Reference

See An Introduction to R for details!

詳細は An Introduction to R を参照.

2 Basic operating instructions / 基本的な操作

 ↓ An example of R code (R script or R program, with sections highlighted in light gray).

  Rコード(Rスクリプト or Rプログラム,薄い灰色で塗りつぶされた箇所)の例

1 + 1
## [1] 2

 ↑ The result of running the R code.

  Rコードを実行した結果

2.1 How do we run the R code on this page? / 実行の方法

en:

  • Using R: Download R
    • Copy and paste directly into the console and press “Enter” (or “Return” on a Mac).
    • Copy and paste into a new script via “File” → “New Script”, select the part to run, then press “Ctrl” + “R”.
  • Using RStudio: After downloading R, Download RStudio
    • Copy and paste directly into the console and press “Enter”.
    • Copy and paste into a script page you created, select the part to run, then press “Ctrl” + “Enter”.

ja:

  • Rを利用:Rをダウンロード
    • コンソールに直接コピーアンドペーストして「Enter」(Macの場合は「Return」)
    • 「ファイル」→「新しいスクリプト」にコピーアンドペーストして,実行する箇所を選択 → 「Ctrl」+「R」
  • RStudioを利用:Rをダウンロードしてから RStudioをダウンロード
    • コンソールに直接コピーアンドペーストして「Enter」
    • 作成したスクリプトページにコピーアンドペーストして,実行する箇所を選択 → 「Ctrl」+「Enter」

2.2 Basic arithmetic operations / 四則演算

1 + 1  # addition 
## [1] 2
2 - 3  # subtraction 
## [1] -1
2 * 3  # multiplication 
## [1] 6
2 / 3  # division 
## [1] 0.6666667

2.3 Comment out / コメントアウト

Anything after the # symbol is commented out (i.e., not executed). It’s useful for writing notes to yourself.

# 記号から後ろはコメントアウトされる(=実行されない). 自分用のメモを書いておくのに便利.

1 + 2 + 10
## [1] 13
1 + 2 # + 10
## [1] 3

2.4 Power, square root, log, exponent / べき乗,平方根,対数,指数

2 ^ 3  # 2 to the power of 3 
## [1] 8
sqrt(16)  # square root 
## [1] 4
log(10)  # natural logarithm 
## [1] 2.302585
exp(1)  # exponential, e = Napier's constant 
## [1] 2.718282

2.5 Help / ヘルプ

Check the functionality and usage of a function.

関数の機能や使い方を調べる.

?exp
help(exp)  # same as above

2.6 Objects / オブジェクト

Users can define any number as an “object.”

By assigning a number to an “object,” we can use that number repeatedly in multiple places.

ユーザーは任意の数字を適当な「オブジェクト」として定義することができる. 数値を「オブジェクト」に割り当てることで,数値を複数の箇所で繰り返し使うことができる.

To assign a value, use the format variableName <- value.

The <- operator is used for assignment and is created by combining the < (less than) symbol with the - (hyphen).

オブジェクト名 <- 数値」の形式で割り当てる. 「<-」は割り当て(または代入)を行う演算子で,「<」(小なり)と「-」(ハイフン)を組み合わせて使用.

x <- 1  # "x" is the object name
x
## [1] 1

Note: Lowercase x and uppercase X are treated as different.

注:小文字 x と大文字 X は区別される.

We can use this object x in calculations.

このオブジェクトを計算に使うことができる.

x + 2
## [1] 3
x <- 10  # overwrite (override) 
x + 5
## [1] 15

The variable name must start with an alphabet letter.

For the second character and beyond, we can use numbers or underscores.

However, we cannot use operators or special characters like + - * / ( ) [ ] ! ? < > = | ^ # $ % & etc.

オブジェクト名はアルファベットではじめる. 2文字目以降は数字やアンダーバーを使ってよい. 演算記号など(+ - * / ( ) [ ] ! ? < > = | ^ # $ % & etc.)は使用不可.

x_3digit <- 500

2.7 Vectors / ベクトル

So far, we’ve been considering scalar numbers, but we can also work with numeric vectors.

To create a vector, use the c function, specifying the elements of the vector as arguments.

上ではスカラーの数字を考えていたが,数ベクトル(すうベクトル)を扱うこともできる. ベクトルを作成するには c 関数を使い,ベクトルの要素を引数として指定する.

c(1, 2, 6)  # combine values into vector
## [1] 1 2 6

Missing values are represented by NA.

欠損値 (missing value) は NA で表す.

c(1, NA, 6)
## [1]  1 NA  6

To generate a sequence of consecutive integers, the colon : operator is useful.

連続する整数のベクトルを生成するにはコロン : を使うのが便利.

1:5
## [1] 1 2 3 4 5
100:105
## [1] 100 101 102 103 104 105

To sum all the elements of a vector, we can use the sum function.

ベクトルの要素をすべて足し合わせる.

sum(c(1, 2, 6))  # sum of 1, 2, 6 
## [1] 9

2.7.1 Assignment to objects / オブジェクトへの代入

Just like scalars, vectors can also be assigned to variables.

ベクトルもスカラーと同様にオブジェクトに代入することができる.

x <- c(1, 2, 6)  # assign vector to object "x"
x
## [1] 1 2 6
sum(x)  # sum of 1, 2, 6
## [1] 9
x + 10
## [1] 11 12 16

2.7.2 Extract a portion of the vector / ベクトルの一部を取り出す

To extract specific elements from a vector, we can use functions like min (which returns the smallest value in the vector), or we can directly specify the position of the element using [ ].

ベクトルの特定の要素を抽出するには,min (ベクトルの要素のうち最小の値を返す関数)のような関数を使ったり,あるいは [ ] を使って何番目の要素かを直接指定する方法がある.

min(x)  # minimum value
## [1] 1
max(x)  # maximum value
## [1] 6
x[2]  # extract 2nd value
## [1] 2
x[c(2, 3)]  # extract 2nd and 3rd values
## [1] 2 6

2.7.3 Multiple vectors / 複数のベクトル

We can also perform operations on multiple vectors.

複数のベクトルに対して演算することもできる.

x <- c(1, 2, 6)
x2 <- c(1, 3, 4)
x + x2
## [1]  2  5 10

The product of a vector and a scalar is calculated as a vector where each element is multiplied by the scalar.

ベクトルとスカラーの積はベクトルの各要素とスカラーの積のベクトルとして計算される.

x * 10
## [1] 10 20 60

3 Dataframe / データフレーム

We can combine vectors to create a data frame consisting of rows and columns.

Note that the elements of the vectors must correspond to each other (e.g., the n-th element of the first vector and the n-th element of the second vector should represent data for the same person or firm).

ベクトルを束ねて行と列からなるデータフレームを作成できる. ただし,ベクトルの各要素は互いに対応していなければならない(例:1つ目のベクトルのn番目の要素と,2つ目のベクトルのn番目の要素は,同じ人や同じ企業のデータが割り当てられている).

3.1 Create data frames / データフレームを作成する

To create a data frame, use the data.frame function, specifying the arguments as column_name (variable name) = vector_object.

データフレームを作成するには data.frame 関数を使い,引数として「列名(変数名) = ベクトルのオブジェクト」を指定する.

beatles_name <- c("John", "Paul", "George", "Ringo") 
beatles_born <- c(1940, 1942, 1943, 1940)  # year of birth 
beatles_decease <- c(1980, NA, NA, NA)  # year of death 
beatles_height <- c(179, 180, 178, 170)  # in cm 
beatles <- data.frame(
  name = beatles_name, 
  born = beatles_born, 
  decease = beatles_decease, 
  height = beatles_height
  )
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

We can also create it in the following way.

以下のように作成することもできる.

beatles2 <- 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)
  )
beatles2
##     name born decease height
## 1   John 1940    1980    179
## 2   Paul 1942      NA    180
## 3 George 1943      NA    178
## 4  Ringo 1940      NA    170

3.2 Extract a portion of the data frame / データフレームの一部を取り出す

To extract specific elements from a data frame, we can use [ ] to specify the row and column numbers, or use the $ symbol to specify the column name (variable name) in the format data_frame_name$column_name.

データフレームの特定の要素を抽出するには, [ ] を使って何行目・何列目かを指定したり,あるいは「データフレーム名$列名」のように $ (ドル)記号を使って列名(変数名)を指定する.

beatles[1, 2]  # 1st row (John) and 2nd column (born)
## [1] 1940
beatles[1:2, 2:3]
##   born decease
## 1 1940    1980
## 2 1942      NA
beatles[1:2, c("born", "decease")]  # same as above
##   born decease
## 1 1940    1980
## 2 1942      NA
beatles[1, ]  # 1st row (John)
##   name born decease height
## 1 John 1940    1980    179
beatles[, 2]  # 2nd column (born)
## [1] 1940 1942 1943 1940
beatles[, "born"]  # same as above
## [1] 1940 1942 1943 1940
beatles$born  # column named "born" (year of birth)
## [1] 1940 1942 1943 1940

3.3 Change the value of the data frame / データフレームの値を変更する

Just like when modifying the value of scalar or vector objects, we can overwrite the values using <-.

スカラーやベクトルのオブジェクトの値を変更する場合と同様に <- で上書きできる.

beatles[3, "decease"] <- 2001  # George 
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

3.4 Create new variable (column) / 新しい変数(列)を追加する

We can add a new variable to a dataset by using the format dataset$new_variable_name <- contents_of_new_variable (such as a vector).

データセット$新しい変数の名前 <- 新しい変数の中身(ベクトルなど)」 のようにして追加できる.

beatles$primary_role <- c("vocal", "vocal", "guitar", "drum")
beatles
##     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

4 Loading CSV file / CSVファイルを読み込む

As an example, let’s load the Titanic passenger data from the file titanic3_csv.csv.

例としてタイタニック号の乗客データ titanic3_csv.csv を読み込む.

元データは http://biostat.mc.vanderbilt.edu/DataSets (既にリンク切れ)から取得したもので,名前などの一部変数を除外している.

参照:Titanic:タイタニック号乗客者の生存状況(年齢や性別などの13項目)の表形式データセット

  • pclass: Ticket Class / 旅客クラス
  • survived: = 1 if survived, = 0 if not survived
  • sex: female or male
  • age: age / 年齢
  • sibsp: the number of siblings/spouses / 同船する兄弟と配偶者の数
  • parch: the number of parents/children / 同船する親と子供の数
  • embarked: port of embarkation / 出港地
    • C=Cherbourg(仏・シェルブール), Q=Queenstown, S=Southampton

4.1 read.csv

Step 1.

Download the CSV file from the Moodle page of the class or from GitHub and save it in an appropriate folder, such as the “ws_stat” (workspace for statistics) folder directly under the C drive.

授業の Moodle ページまたは GitHub から CSV ファイルをダウンロードして適当なフォルダに保存する. たとえばCドライブ直下の「ws_stat」(workspace for statistics) フォルダに保存する.

Step 2.

Use the setwd function to specify the folder where you saved the file as the working directory. We can check the specified working directory with the getwd function (leave the parentheses empty).

setwd 関数を使って保存したフォルダを作業ディレクトリとして指定する. getwd 関数で指定された作業ディレクトリを確認できる(カッコの中には何も書かない).

Step 3.

Use the read.csv function, specifying the file name as an argument, to load the file.

read.csv 関数でファイル名を引数として指定して読み込む.

setwd("c://ws_stat")  # set working directory
getwd()  # get working directory
## [1] "c:/ws_stat"
titanic <- read.csv("titanic3_csv.csv")

Note: When running an .rmd file chunk by chunk, the working directory may reset after each chunk is executed.

注:.rmd ファイルを開いてチャンクごとに実行する場合,チャンクの実行が終わると作業ディレクトリがリセットされる.

If the file contains Japanese (or Chinese, Korean, or any other non-alphabet) characters, it might cause errors, so it’s recommended for beginners to create and use files without including Japanese characters.

ファイルに日本語が含まれるとエラーが出る場合があるので,初心者のうちは日本語を含めずにファイルを作成・使用するのがおすすめ.

4.2 read.csv + file.choose

If the working directory settings do not work, execute the following line to load the CSV file. The “Select File” screen will appear, from which you can select the CSV file to be read.

作業ディレクトリの設定がうまくできない場合は,次の行を実行してCSVファイルを読み込む.実行すると「ファイルを選択」画面が出てきて,そこから読み込むCSVファイルを選択することができる.

titanic <- read.csv(file.choose())

4.4 Data overview / データの概観

We can use the str function mentioned earlier to check the structure of the data frame, and the head function to display the first few rows (the default is 6 rows).

先ほど取り上げた str 関数を利用してデータフレームの構造を確認したり,head 関数を利用して最初の数行(デフォルトは6行)のみを表示させる.

str(titanic)
## 'data.frame':    1309 obs. of  8 variables:
##  $ pclass  : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ survived: int  1 1 0 0 0 1 1 0 1 0 ...
##  $ sex     : chr  "female" "male" "female" "male" ...
##  $ age     : num  29 0.92 2 30 25 48 63 39 53 71 ...
##  $ sibsp   : int  0 1 1 1 1 0 1 0 2 0 ...
##  $ parch   : int  0 2 2 2 2 0 0 0 0 0 ...
##  $ fare    : num  211 152 152 152 152 ...
##  $ embarked: chr  "S" "S" "S" "S" ...
head(titanic)
##   pclass survived    sex   age sibsp parch     fare embarked
## 1      1        1 female 29.00     0     0 211.3375        S
## 2      1        1   male  0.92     1     2 151.5500        S
## 3      1        0 female  2.00     1     2 151.5500        S
## 4      1        0   male 30.00     1     2 151.5500        S
## 5      1        0 female 25.00     1     2 151.5500        S
## 6      1        1   male 48.00     0     0  26.5500        S

Using the View function opens a window that displays the entire dataset.

View 関数を使うとデータセット全体を表示するウィンドウが表示される.

View(titanic)

4.5 Output file / ファイルを出力

We can export datasets or other processed data in R to a file format such as CSV.

Rで加工したデータセットなどを CSV などのファイル形式で出力することができる.

4.5.1 Case 1. If the working directory has already been specified

The file will be exported to the working directory that was previously set using setwd.

既に作業ディレクトリを指定している場合には,先ほど setwd で指定した作業ディレクトリに出力される.

titanic_head <- head(titanic)
write.csv(titanic_head, "titanic_first_6_rows.csv")

4.5.2 Case 2. If the working directory has not been specified

When we run the code from Case 1, the file will be exported to the default working directory. As mentioned earlier, we can check the default directory using getwd().

作業ディレクトリを指定していない場合には,Case 1 のコードを実行するとデフォルトで指定されている作業ディレクトリに出力される. デフォルトのディレクトリは先述のとおり getwd() で確認できる.

4.5.3 Case 3. If you want to save the file in a folder different from the specified working directory

First, create the destination folder (e.g., a new_dir folder directly under ws_stat).

指定した作業ディレクトリとは別のフォルダに保存する場合には,先に保存先フォルダを作成する(例:ws_stat 直下の new_dir フォルダ).

titanic_head <- head(titanic)
write.csv(titanic_head, "c://ws_stat/new_dir/titanic_first_6_rows.csv")

5 Take home messages

en:

  • If you’re unsure about something, check the help:
    • Use ?function_name or help(function_name)
    • If that doesn’t help, try searching on Google, asking ChatGPT, or looking on YouTube, etc.
  • To assign a value to an object: object_name <- content (scalar, vector, data frame, etc.)
  • To read a CSV file: read.csv("file_name")

ja:

  • 分からないことがあればヘルプを見る
    • ヘルプは ?関数名 または help(関数名)
    • それでも分からなければ,Google で検索,ChatGPT に相談,YouTube で検索,etc.
  • オブジェクトへの代入は オブジェクト名 <- 中身(スカラー or ベクトル or データフレーム etc.)
  • CSV ファイルの読み込みは read.csv("ファイル名")