![見出し画像](https://assets.st-note.com/production/uploads/images/96618222/rectangle_large_type_2_46580e880e8d48931e873dbb72e6d9bb.png?width=1200)
Rをつかう単純な計算のための備忘録
Rを使い始めた頃に参照していたものの1つは『データ解析環境「R」』(工学社発行)という本であった。著者は、舟尾暢男・高浪洋平の2氏。本に書き込みをしながら読んだ。有意義な本であった。
まず、その本に書き込んだメモを見ながら、Rの使い方を復習してみようと思う。そうすることで、しばらく使わないでいたあとにまごつかないようにすることができるだろう。
別の本(注)も、昔真剣に取り組んだことがある。その本の巻末に「補遺 RとS-PLUSの備忘録」というものがあり、これも復習してみようと思っている。Rを自由に使えるならば、わざわざPythonなどのプログラミング言語を新たに学ぶ必要は私にとってはない。(表計算ソフトも無用である。)
[注]
B.エベリット『RとS-PLUSによる多変量解析』(シュプリンガー・ジャパン)
1. 表計算ソフトのような計算
まず、1から12までの数からマトリックス(行列)を作り、その行や列を操作してみる。
a <- matrix(1:12,3)
a
![](https://assets.st-note.com/img/1674825835748-oGqPLbOimL.png?width=1200)
b <- a[2,] + a[3,]
b
![](https://assets.st-note.com/img/1674825891352-t4eMkZkjEt.png?width=1200)
c <- rbind(a,b)
c
![](https://assets.st-note.com/img/1674825945378-cdA2diiGek.png?width=1200)
d <- c[c(1,4),]
d
![](https://assets.st-note.com/img/1674825996974-rClgMwXMEi.png?width=1200)
上の例で、「c(1,4)」の部分は、「c(-2,-3)」や「-c(2,3)」と同じ。マイナス記号は、排除を意味する。
rownames(d)[1] <- "a(r1)"
d
![](https://assets.st-note.com/img/1674826039190-Tvxdm4NmSd.png?width=1200)
mydata <- matrix(c(70,30,45,5),2,byrow = T)
mydata
![](https://assets.st-note.com/img/1674824693556-4O4UGedwtZ.png?width=1200)
addmargins(mydata, margin = 1:2)
![](https://assets.st-note.com/img/1674873482095-MdWyNKW262.png?width=1200)
グラフ化してみる。図で日本語を使うためにはMacの場合、par(family="HiraKakuProN-W3")などとフォントを指定する。棒グラフはbarplot()関数を使う。
par(family="HiraKakuProN-W3")
barplot(mydata,xlab="性別",names=c("男","女"),col=c("blue","red"))
![](https://assets.st-note.com/img/1674824779662-HJnu3qNuqT.png?width=1200)
棒を横に並べる場合には、beside = TRUEとする。
par(family="HiraKakuProN-W3")
barplot(mydata,names=c("男","女"),col=c("blue","red"), beside=T)
![](https://assets.st-note.com/img/1675046174652-iI1pSAPIoH.png)
パーセントの計算
prop.table()関数で、行方向、あるいは、列方向の比率を計算する。
# 行パーセントの計算
m1 <- prop.table(mydata,1)
rownames(m1) <- c("male","female")
colnames(m1) <- c("yes","no")
m1
![](https://assets.st-note.com/img/1674825362385-Vfc3SYu1Og.png?width=1200)
行と列を入れ替えて100をかける。性別が表頭に来るようにする。
m2 <- t(m1)*100
m2
![](https://assets.st-note.com/img/1674824901148-vGTT7HYWMB.png?width=1200)
棒グラフ
barplot(m2,xlab="sex",col=c("blue","red"),
legend=T,args.legend = list(x = "bottomright"))
![](https://assets.st-note.com/img/1674824988393-c9Q7LbAnST.png?width=1200)
帯グラフ
barplot(m2,horiz=T,xlab="respose",col=c("blue","red"),
legend=T,args.legend = list(x = "bottomright"))
![](https://assets.st-note.com/img/1674825047800-9hWpqWXqAY.png?width=1200)
列の入れ替え。2列目が1列目に、1列目が2列目に。
m3 <- m2[,c(2,1)]
m3
![](https://assets.st-note.com/img/1675045417655-ZqkfvrRDzA.png)
モザイク図
mosaicplot(m2,color = T,main = "")
![](https://assets.st-note.com/img/1674825094284-XrPAXyLBYY.png?width=1200)
mosaicplot(t(m2),color = T,main = "")
![](https://assets.st-note.com/img/1674825152934-YTdiYg70du.png)
カイ2乗検定
m2
chisq.test(m2)
chisq.test(m2, simulate.p.value=TRUE)
fisher.test(m2)
male female
yes 70 90
no 30 10
Pearson's Chi-squared test with Yates' continuity correction
data: m2
X-squared = 11.281, df = 1, p-value = 0.0007829
Pearson's Chi-squared test with simulated p-value (based on
2000 replicates)
data: m2
X-squared = 12.5, df = NA, p-value = 0.0009995
Fisher's Exact Test for Count Data
data: m2
p-value = 0.0006504
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.1063153 0.5936350
sample estimates:
odds ratio
0.2609721
二つの比率の差の検定
# サンプルaとサンプルbの比率を設定
p1 <- 0.468
p2 <- 0.363
# サンプルaとサンプルbのサイズを設定
n1 <- 188
n2 <- 457
# 両サンプルを結合した場合の比率を計算(母比率の推定値として)
p_hat <- (p1 * n1 + p2 * n2) / (n1 + n2)
# 検定統計量zを計算
z <- (p1 - p2) / sqrt(p_hat * (1 - p_hat) * (1/n1 + 1/n2))
# p値を計算
p_value <- 2 * (1 - pnorm(abs(z)))
# 結果を表示
cat("検定統計量 z =", z, "\n")
cat("p値 =", p_value, "\n")
# 有意水準0.05での検定
if (p_value < 0.05) {
cat("2つの比率に有意な差があります。\n")
} else {
cat("2つの比率に有意な差はありません。\n")
}
```
行列の行名と列名をまとめて定義する(dimnames)
rownames()やcolnames()を使って行名や列名を定義することができるが、一度にそれらをおこなうには、dimnames()関数を使う。
x <- matrix(seq(12),nrow=4)
dimnames(x) <- list(c("R1","R2","R3","R4"), c("C1","C2","C3"))
x
![](https://assets.st-note.com/img/1674892777256-ltJ5LyWbmd.png?width=1200)
x <- matrix(seq(12),nrow=4)
dimnames(x) <- list(paste("row", seq(4)), paste("col", seq(3)))
x
![](https://assets.st-note.com/img/1674892840949-nEOmvfWb6L.png?width=1200)
2. データフレーム
データフレームの作成は、data.frame(vector1, vector2, …)。
height <- c(50,70,45,80,100)
weight <- c(120,140,100,200,190)
age <- c(20,40,41,31,33)
names <- c("Bob","Ted","Alice","Mary","Sue")
sex <- c("Male","Male","Female","Female","Female")
data <- data.frame(names,sex,height,weight,age)
data
![](https://assets.st-note.com/img/1674893509125-MzM26QvcwQ.png?width=1200)
年齢のデータを取り出すためには、data$ageでもいいし、data[,"age"]でもいい。data[,5]も同じ結果。
data[3:5,5]とすると、3行目から5行目まで(3:5)のageの数値(5列目)が表示される。これは、data[-c(1:2),5]、あるいは、data[c(-1,-2),5]としてもよい。
列の平均
数値が入っている列で平均を計算する。apply()関数を利用。meanの前の2は、列方向を意味する。
apply(data[,c(3,4,5)],2,mean) # 平均
![](https://assets.st-note.com/img/1675478332411-j0pn106s1F.png?width=1200)
集計(tabulation)
単純集計やクロス集計をおこなう。
table(data$sex)
table(data$height, data$sex)
![](https://assets.st-note.com/img/1675321954989-f1hiJPeqI2.png?width=1200)
度数分布やヒストグラムを作成する場合には、データをどのように分割するかが問題になる。以下はcut()関数の説明。
Convert Numeric to Factor
Description
cut divides the range of x into intervals and codes the values in x according to which interval they fall. The leftmost interval corresponds to level one, the next leftmost to level two and so on.
breaks <- seq(40,100,by=20)
table(cut(data$height,breaks))
![](https://assets.st-note.com/img/1674894498064-cR2kMqYwUc.png?width=1200)
各範囲は、左の境界がopenで、右の境界がclosed。つまり、「超える」と「以下」。普通の「a以上、b未満」という区切り方と違う。
pie(result, labels = c("A","B","C"), col = rainbow(3))
![](https://assets.st-note.com/img/1674894907181-iWwMhtHQcY.png)
ヒストグラム
hist(data$height,breaks)
![](https://assets.st-note.com/img/1674895401446-iSY5iXQbp1.png?width=1200)
各範囲がa以上b未満(右端を除き)とするためには、right = FALSE, include.lowest = TRUEと設定する。[a,b)という設定。
hist(data$height, breaks = breaks,right = F,include.lowest = T)
![](https://assets.st-note.com/img/1674906808746-JSYPwpEb09.png?width=1200)
freq <- cut(data$height, breaks=breaks, right=F, include.lowest=TRUE)
table(freq)
![](https://assets.st-note.com/img/1674907134213-H2qoMgJHWy.png?width=1200)
散布図
plot(x=data$height, y=data$weight)
result <- lm(weight ~ height, data = data)
abline(result)
![](https://assets.st-note.com/img/1675325495321-rqYLw5fZIh.png?width=1200)
3. ベクトルに用いる関数
合計、要約、標準偏差、丸め、ヒストグラム、箱ひげ図
x <- 1:100
sum(x)
## [1] 5050
summary(x)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.00 25.75 50.50 50.50 75.25 100.00
sd(x)
## [1] 29.01149
round(29.01149,digits=2)
## [1] 29.01
x <- rnorm(1000, mean=0, sd=1)
hist(x)
boxplot(x)
![](https://assets.st-note.com/img/1675160839589-mbUTQfSNcz.png?width=1200)
![](https://assets.st-note.com/img/1675160857443-EAkxZOJJLp.png?width=1200)
この記事が気に入ったらサポートをしてみませんか?