# 向量

``````> x = 2:9
> x
[1] 2 3 4 5 6 7 8 9
> x+1
[1]  3  4  5  6  7  8  9 10
> x-2.1
[1] -0.1  0.9  1.9  2.9  3.9  4.9  5.9  6.9
> x*5
[1] 10 15 20 25 30 35 40 45
> x*x
[1]  4  9 16 25 36 49 64 81
> y=2*x
> x*y
[1]   8  18  32  50  72  98 128 162
> y-x
[1] 2 3 4 5 6 7 8 9
> z = c(1,2,3,4)
> z^z
[1]   1   4  27 256
> cos(x*pi)
[1]  1 -1  1 -1  1 -1  1 -1
> cos(0.5*x*pi)
[1] -1.000000e+00 -1.836910e-16  1.000000e+00  3.061516e-
16 -1.000000e+00
[6] -4.286122e-16  1.000000e+00  5.510729e-16
> length(x)
[1] 8
> sum(x)
[1] 44
> prod(x)
[1] 362880
> cumsum(x)
[1]  2  5  9 14 20 27 35 44
> x = c(3, "abc", 4)
> x
[1] "3"   "abc" "4"
> w = c(x,y)
> w
[1] "3"   "abc" "4"   "4"   "6"   "8"   "10"  "12"  "14"
"16"  "18"
>
> x = 1:5
> length(x)
[1] 5
> y=1:12
> y
[1]  1  2  3  4  5  6  7  8  9 10 11 12
> matrix(y, 3,4)
[,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> dim(x)
NULL
> dim(y)
NULL
> dim x

> w = matrix(y, 3,4)
> dim(w)
[1] 3 4
> x
[1] 1 2 3 4 5
> x=x[-c(2,4)]
> x
[1] 1 3 5
> y
[1]  1  2  3  4  5  6  7  8  9 10 11 12
> y[c(2,3,4)]=c(12,13,14)
> y
[1]  1 12 13 14  5  6  7  8  9 10 11 12
> x
[1] 1 3 5
>
> x=3:7
> x
[1] 3 4 5 6 7
> y=c(n1=1, n2=2, n3=3)
> y
n1 n2 n3
1  2  3
> y[c(n1,n3)]

> y[c("n1","n3")]
n1 n3
1  3
> y[c(1,3)]
n1 n3
1  3
> z=c(一=1, 二=2, 三=3)
> z

1  2  3
> names(z)
[1] "一" "二" "三"
> w = 3:5
> w
[1] 3 4 5
> names(v) = c("叁", "肆", "伍"); w

> names(w) = c("叁", "肆", "伍"); w

3  4  5```
```

# 向量索引

``````> x = c(3,5,9)
> x[2]
[1] 5
> x
[1] 3 5 9
> x[c(1,3)]
[1] 3 9
> x[c(3)]
[1] 9
> x[1:2]
[1] 3 5
> y=x[1:2]
> y
[1] 3 5
>
> x=1:4
> y=5:8
> xy=rbind(x,y)
> x
[1] 1 2 3 4
> y
[1] 5 6 7 8
> xy
[,1] [,2] [,3] [,4]
x    1    2    3    4
y    5    6    7    8
> xyc = cbind(x,y)
> xyc
x y
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
> is.array(xy)
[1] TRUE
> is.array(x)
[1] FALSE
> is.matrix(xy)
[1] TRUE
> is.matrix(x)
[1] FALSE
> x=array(1:12, dim=c(3,4))
> x
[,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> length(x)
[1] 12
> nrow(x)
[1] 3
> ncol(x)
[1] 4
> x[1,]
[1]  1  4  7 10
> x[,2]
[1] 4 5 6
> x[1,2]
[1] 4
> y=x[1, c(2,3)]
> y
[1] 4 7
> z=x(c(1,2))

> z=x[c(1,2)]
> z
[1] 1 2
> z=x[c(10,11)]
> z
[1] 10 11
> x
[,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> x[2:3, 2:3]
[,1] [,2]
[1,]    5    8
[2,]    6    9
>```
```

page revision: 1, last edited: 26 Oct 2011 00:50