LoginSignup
5
11

More than 5 years have passed since last update.

【R入門】R言語の基本的な使い方

Last updated at Posted at 2018-01-12

統計とR言語の勉強をしています。
「Rによるやさしい統計学」の写経で勉強。

実行環境

  • Windows10 Pro 64bit
  • R:3.4.3
  • RStudio:1.1.383 RStudioのConsoleを使って実行しています

基本計算

計算機のように数字と+の符号を打つだけで計算してくれます。
sum関数を使っても同じ結果です。

> 10+13+8+15+8
[1] 54
> sum(10,13,8,15,8)
[1] 54

変数に入れ込むことで計算が(計算機ではなく)プログラムらしくなります。

> testa <- c(10,13,8,15,8)
> testa
[1] 10 13  8 15  8
> sum(testa)
[1] 54

平均を求めるのであれば、以下の3つの方法があります(変数testaは上の続きです)。length関数はデータの個数を出力します。当然、mean関数を使うのが最もシンプルです。

> sum(testa)/5
[1] 10.8
> sum(testa)/length(testa)
[1] 10.8
> mean(testa)
[1] 10.8

median関数は中央値をtable関数は度数分布を出力します。

> median(testa)
[1] 10
> table(testa)
testa
 8 10 13 15 
 2  1  1  1 

分散と標準偏差

地味に計算していきます。平均、偏差の二乗和、分散、標準偏差の順に計算しています。

> testaave <- mean(testa)
> testaave
[1] 10.8

# 平均との差
> testadev <- testa - testaave
> testaave
[1] 10.8
> testadev
[1] -0.8  2.2 -2.8  4.2 -2.8

# 偏差の2乗
> testadevsqr <- testadev^2
> testadevsqr
[1]  0.64  4.84  7.84 17.64  7.84

#偏差の2乗和
> testadevsqrsum <- sum(testadevsqr)
> testadevsqrsum
[1] 38.8

#分散(不偏分散でない)
> testavar <- testadevsqrsum/length(testa)
> testavar
[1] 7.76

#標準偏差
> sqrt(testavar)
[1] 2.785678

varという関数があるのですが、不偏分散なので注意が必要です。上で算出した7.76と結果が異なります。

> var(testa)
[1] 9.7

標準偏差はsdです。こちらも不偏分散の平方根なので上で算出した2.785678と結果が異なります。

> sd(testa)
[1] 3.114482

その他

maxとminという関数もあります。最大値と最小値です。

> max(testa)
[1] 15
> min(testa)
[1] 8
5
11
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
5
11