3.4.1.5 ベクトルへのアクセス
x=c(2.718, 3.14, 1.414, 47405)
names(x)=c("e","pi","sqrt2","zipcode")
どの要素を返すか数値で指定
x[c(2,4)]
## pi zipcode
## 3.14 47405.00
どの要素を除外するか指定
x[c(-1,-3)]
## pi zipcode
## 3.14 47405.00
それぞれの要素を返すか指定する
x[c(FALSE,TRUE,FALSE,TRUE)]
## pi zipcode
## 3.14 47405.00
要素名を指定する
x[c("pi","zipcode")]
## pi zipcode
## 3.14 47405.00
3.4.2 ファクター型
x=c("high","medium","low", "high","medium")
ファクター型に変換
xf=factor(x)
xf
## [1] high medium low high medium
## Levels: high low medium
factor型を数値に変換
as.numeric(xf)
## [1] 1 3 2 1 3
levelsを指定
xfo=factor(x, levels=c("low","medium","high"), ordered=TRUE)
xfo
## [1] high medium low high medium
## Levels: low < medium < high
as.numeric(xfo)
## [1] 3 2 1 3 2
既に存在しているfactor型のlevelを変更
x=c("high","medium","low", "high","medium")
xf=factor(x)
xf
## [1] high medium low high medium
## Levels: high low medium
as.numeric(xf)
## [1] 1 3 2 1 3
xf=factor(xf, levels=c("low","medium","high"), ordered=TRUE)
xf
## [1] high medium low high medium
## Levels: low < medium < high
as.numeric(xf)
## [1] 3 2 1 3 2
levelsの名前を変えたい場合
xfol=factor(xf, levels=c("low","medium","high"), ordered=TRUE, labels = c("bottom", "middle", "top"))
xfol
## [1] top middle bottom top middle
## Levels: bottom < middle < top