I.関数を作ると便利

Rの関数の作り方を学びます。

II.関数は便利

関数を使うと便利です。

例えば、次のような試験結果のデータがあるとします。

a、b、c、、、は名前で、goi1、goi2、goi3、、、は語彙試験の回数です。

library(tidyverse)
goi_wide <- read_csv("https://pastebin.com/raw/pCvBzgBu")
goi_wide
## # A tibble: 11 x 7
##    name   goi1  goi2  goi3  goi4  goi5  goi6
##    <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
##  1 a         0     0     4     1     4     5
##  2 b         4     4     4     4     6     0
##  3 c         8     5     4     6     8     5
##  4 d         0     0     4     7    10     5
##  5 e         6     2    10     8     8     8
##  6 f         4     0     3     5     7     5
##  7 g         6     3     2     5     6     6
##  8 h         7     4     9    10     9    10
##  9 i         6     3     6     3     5     2
## 10 j         6     0     3     6     8     0
## 11 k         4     1     0     3     5     4

III.データをたて長に変換

集計しやすいように、よこ長データをたて長データに変換します。

列は名前と試験名と得点の列にまとめられ、行は受験者の試験結果です。

このような形にすると、新たなデータが下の行に加えられても列は動かないのでコードを書きやすいです。 また、グラフ作成のライブラリggplotはこのたて長データに対応しています。

goi_wide %>% 
  pivot_longer(
    goi1:goi6,
    names_to = "test",
    names_prefix = "goi",
    values_to = "score"
  ) -> goi_long
goi_long
## # A tibble: 66 x 3
##    name  test  score
##    <chr> <chr> <dbl>
##  1 a     1         0
##  2 a     2         0
##  3 a     3         4
##  4 a     4         1
##  5 a     5         4
##  6 a     6         5
##  7 b     1         4
##  8 b     2         4
##  9 b     3         4
## 10 b     4         4
## # … with 56 more rows

IV. 関数の作成

列を指定すると平均を集計するmyfunctionという名の関数を作ります。

myfunction <- function(df_long, col_name){
  col_name <- enquo(col_name)
  df_long %>%
    group_by(!!col_name) %>%
    summarise(mean = round(mean(score), 3))
}

V. 関数の実行

受講者一人ひとりの平均を出します。

myfunction(goi_long, name)
## # A tibble: 11 x 2
##    name   mean
##    <chr> <dbl>
##  1 a      2.33
##  2 b      3.67
##  3 c      6   
##  4 d      4.33
##  5 e      7   
##  6 f      4   
##  7 g      4.67
##  8 h      8.17
##  9 i      4.17
## 10 j      3.83
## 11 k      2.83

試験ごとの平均点を出します。

myfunction(goi_long, test)
## # A tibble: 6 x 2
##   test   mean
##   <chr> <dbl>
## 1 1      4.64
## 2 2      2   
## 3 3      4.46
## 4 4      5.27
## 5 5      6.91
## 6 6      4.54

To be continued.