noteで公表。

マトリックスの内部の計算

a <- matrix(1:12,nrow=3, byrow = F)
a
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
b <- a[2,] + a[3,]
b
## [1]  5 11 17 23
c <- rbind(a,b)
c
##   [,1] [,2] [,3] [,4]
##      1    4    7   10
##      2    5    8   11
##      3    6    9   12
## b    5   11   17   23
d <- c[c(1,4),]
d
##   [,1] [,2] [,3] [,4]
##      1    4    7   10
## b    5   11   17   23
d <- c[-c(2,3),]
d
##   [,1] [,2] [,3] [,4]
##      1    4    7   10
## b    5   11   17   23
d <- c[c(-2,-3),]
d
##   [,1] [,2] [,3] [,4]
##      1    4    7   10
## b    5   11   17   23
rownames(d)[1] <- "a(r1)"
d
##       [,1] [,2] [,3] [,4]
## a(r1)    1    4    7   10
## b        5   11   17   23

2×2表

mydata <- matrix(c(70,30,45,5),2,byrow = T)
mydata
##      [,1] [,2]
## [1,]   70   30
## [2,]   45    5
addmargins(mydata, margin = 1:2)
##            Sum
##      70 30 100
##      45  5  50
## Sum 115 35 150
par(family="HiraKakuProN-W3")
barplot(mydata,xlab="性別",names=c("男","女"),col=c("blue","red"))

par(family="HiraKakuProN-W3")
barplot(mydata,names=c("男","女"),col=c("blue","red"), beside=T)

# 行パーセントの計算
m1 <- prop.table(mydata,1)
rownames(m1) <- c("male","female")
colnames(m1) <- c("yes","no")
m1
##        yes  no
## male   0.7 0.3
## female 0.9 0.1
m2 <- t(m1)*100
m2
##     male female
## yes   70     90
## no    30     10
barplot(m2,xlab="sex",col=c("blue","red"),legend=T,args.legend = list(x = "bottomright"))