R语言基础知识学习(一):R中的向量的产生与访问

 

向量是用于存储数值型、字符型或逻辑型数据的一维数组。

(1)用函数c()可以来创建一个向量,如:

> a <- c(1,2,3,4)
> b <- c('china','america','japan')
> c <- c(TRUE,FALSE,TRUE,FALSE)
> ls()
[1] "a" "b" "c"
> ls.str()
a : num [1:4] 1 2 3 4
b : chr [1:3] "china" "america" "japan"
c : logi [1:4] TRUE FALSE TRUE FALSE

上述代码定义三个向量,a,b,c分别存储数值型,字符型和逻辑型变量。

(2)也可以用冒号:来生成向量序列,如

> d <- 1:30
> d
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
[20] 20 21 22 23 24 25 26 27 28 29 30

(3)函数seq可以生成如下的实数序列:
> seq(1, 5, 0.5)
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

也可以这样使用:
> seq(length=9, from=1, to=5)
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

(4)函数rep用来创建一个所有元素都相同的向量:
> rep(1, 30)
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

(5)函数sequence创建一系列连续的整数序列,每个序列都以给定参数的数值结尾:
> sequence(4:5)
[1] 1 2 3 4 1 2 3 4 5
> sequence(c(10,5))
[1] 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5

> sequence(c(1:10))
[1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4
[20] 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2
[39] 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10

(6)gl()函数可以生成不同的水平因子序列,具体用法如下:

gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)

Arguments

n                an integer giving the number of levels.
k                an integer giving the number of replications.
length        an integer giving the length of the result.
labels         an optional vector of labels for the resulting factor levels.
ordered       a logical indicating whether the result should be ordered or not.

如:

> gl(3,5)
[1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
Levels: 1 2 3


> gl(4,4)
[1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
Levels: 1 2 3 4


> gl(20,3)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7
[20] 7 7 8 8 8 9 9 9 10 10 10 11 11 11 12 12 12 13 13
[39] 13 14 14 14 15 15 15 16 16 16 17 17 17 18 18 18 19 19 19
[58] 20 20 20

> gl(3, 5, length=30)
[1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
Levels: 1 2 3

> gl(2, 8, labels = c("Control", "Treat","haha"))
[1] Control Control Control Control Control Control Control
[8] Control Treat Treat Treat Treat Treat Treat
[15] Treat Treat
Levels: Control Treat haha

通过方括号可以访问向量里的元素,如:

> a[1]
[1] 1
> b[1]
[1] "china"
> c[2]
[1] FALSE

也可以一起访问多个元素,如:

> a[c(1,3,4)]
[1] 1 3 4
> b[c(2,3)]
[1] "america" "japan"

访问a向量里的第1,3,4个元素和b向量里的第2,3个元素。注:向量里的元素下标是从1开始的。

人前一杯酒,各自饮完;人后一片海,独自上岸
原文地址:https://www.cnblogs.com/kisen/p/12755670.html