Subsetting data from vector:
[] operator
- By single value
- Slicing
- By vector (integer/logical)
Satisfied given condition
原理是取得某條件的logical vector,再用logical vector取值。
> x <- 11:20
> x
[1] 11 12 13 14 15 16 17 18 19 20
#用[]取得位置1的元素
> x[1]
[1] 11
#用[]取得位置第2-5的元素
> x[2:5]
[1] 12 13 14 15
#用vector取得指定位置的元素
> x[c(1,3,5)]
[1] 11 13 15
#用logical vector取得該位置為TRUE的元素
> y <- (x > 15)
> y
[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
> x[y]
[1] 16 17 18 19 20
#看得出跟上面很像嗎?
#x > 15也是產生一個logical vector塞到x[]裡面
> x[x > 15]
[1] 16 17 18 19 20