使用vector函数可创建指定类型和长度的矢量
> vector("numeric",5) #等价于numeric(5) [1] 0 0 0 0 0 > vector("complex",5) #等价于complex(5) [1] 0+0i 0+0i 0+0i 0+0i 0+0i > vector("logical",5) #等价于logical(5) [1] FALSE FALSE FALSE FALSE FALSE > vector("character",5) #等价于character(5) [1] "" "" "" "" "" > vector("list",5) [[1]] NULL [[2]] NULL [[3]] NULL [[4]] NULL [[5]] NULL
可通过seq来创建序列,seq.int(3,12)等价于3:12,该函数还有更为灵活的用法,除了指定序列的范围外还可指定步长
> seq.int(3,12,2) [1] 3 5 7 9 11
如上面示例所示,该序列包含3到12之间步长为2的数字。seq_along则创建一个从1开始,长度为输入值的序列
> p <- c("Piper", "Peter", "picked", "a", "peck", "of", "pickled", "peppers") > for(i in seq_along(p)) print(p[i]) [1] "Piper" [1] "Peter" [1] "picked" [1] "a" [1] "peck" [1] "of" [1] "pickled" [1] "peppers"
length()函数可查看向量的长度,nchar()函数可查看字符的长度
索引向量
> x <- (1:5)^2 > x [1] 1 4 9 16 25 > x[c(1, 3 ,5)] [1] 1 9 25 > x[c(-2, -4)] [1] 1 9 25 > x[c(TRUE, FALSE, TRUE, FALSE, TRUE)] [1] 1 9 25 > names(x) <- c("one", "four", "nine", "sixteen", "twenty five") > x[c("one", "nine", "twenty five")] one nine twenty five 1 9 25 > which(x > 10) sixteen twenty five 4 5 > which.min(x) one 1 > which.max(x) twenty five 5 >
向量循环和重复
> rep(1:5, 3) [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 > rep(1:5, each = 3) [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 > rep(1:5, times = 1:5) [1] 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 > rep(1:5, length.out = 7) [1] 1 2 3 4 5 1 2 > rep.int(1:5, 3) [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 > rep_len(1:5, 13) [1] 1 2 3 4 5 1 2 3 4 5 1 2 3