1.向量类似于数学中的集合概念
2.用函数c来创建向量
> x <- c(1,2,3,4,5)
> y <- c("apple","pineapple","banana")
> z <- c(TRUE,T,F)
> M <- c(1:100)
> N <- seq(from=1,to=100,by=2)
> L <- seq(from=1,to=100,length.out=5)
> ?rep
> rep(2,5)
[1] 2 2 2 2 2
> rep(2,5)
[1] 2 2 2 2 2
> rep(x,5)
[1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
> rep(x,each=5)
[1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
> rep(x,each=5,times=2)
[1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
[41] 4 4 4 4 4 5 5 5 5 5
3.向量索引
(1)正负整数索引
R的索引是从1开始,而不是从0。其次,R的负数索引不代表逆序索引,而是表示除该绝对值不引用外的其他所有值。
> x <- c(1:100)
> length(x)
[1] 100
> x[1]
[1] 1
> x[0]
integer(0)
> x[-19]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21
[21] 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
[41] 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
[61] 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
[81] 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
> x[c(4:20)]
[1] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> x[c(1,3,15,34,23)]
[1] 1 3 15 34 23
> x[c(-2,3,4)]
Error in x[c(-2, 3, 4)] : only 0's may be mixed with negative subscripts
(2)逻辑向量索引
只输出逻辑值为真的数值
> y <- c(1:10)
> y
[1] 1 2 3 4 5 6 7 8 9 10
> y[c(T,T,F,T,T,F,F,F,T,F)]
[1] 1 2 4 5 9
> y[c(T)]
[1] 1 2 3 4 5 6 7 8 9 10
> y[c(F)]
integer(0)
> y[c(T,F)]
[1] 1 3 5 7 9
> y[c(T,T,F,T,T,F,F,F)]
[1] 1 2 4 5 9 10
> y[c(T,T,F,T,T,F,F,F,T,F,T,F)]
[1] 1 2 4 5 9 NA
> y[y>5]
[1] 6 7 8 9 10
> y[y>5 & y<9]
[1] 6 7 8
> z <- c("one","two","three","four","five")
> z
[1] "one" "two" "three" "four" "five"
> z[ "one" %in% z]
[1] "one" "two" "three" "four" "five"
> z[z %in% c("one","two")]
[1] "one" "two"
> z %in% c("one","two")
[1] TRUE TRUE FALSE FALSE FALSE
> k <- z %in% c("one","two")
> z[k]
[1] "one" "two"
(3)名称索引
> names(y)
NULL
> names(y) <- c("one","two","three","four","five","six","seven")
> y
one two three four five six seven <NA> <NA> <NA>
1 2 3 4 5 6 7 8 9 10
> names(y)
[1] "one" "two" "three" "four" "five" "six" "seven" NA NA NA
> y["one"]
one
1
> y[1]
one
1