矢量

R 中的向量可以具有不同的类型(例如,整数,逻辑,字符)。定义矢量的最常用方法是使用函数 vector()

vector('integer',2) # creates a vector of integers of size 2.
vector('character',2) # creates a vector of characters of size 2.
vector('logical',2) # creates a vector of logicals of size 2.

然而,在 R 中,速记函数通常更受欢迎。

integer(2) # is the same as vector('integer',2) and creates an integer vector with two elements
character(2) # is the same as vector('integer',2) and creates an character vector with two elements
logical(2) # is the same as vector('logical',2) and creates an logical vector with two elements

也可以使用除默认值之外的值创建向量。通常使用函数 c() 来实现此目的。c 是组合或连接的缩写。

c(1, 2) # creates a integer vector of two elements: 1 and 2.
c('a', 'b') # creates a character vector of two elements: a and b.
c(T,F) # creates a logical vector of two elements: TRUE and FALSE.

这里要注意的重要事项是 R 将任何整数(例如 1)解释为大小为 1 的整数向量。数字(例如 1.1),逻辑(例如 T 或 F)或字符(例如’a’)也是如此。因此,你实质上是组合向量,而向量又是向量。

注意你总是需要组合相似的向量。否则,R 将尝试转换相同类型的向量中的向量。

c(1,1.1,'a',T) # all types (integer, numeric, character and logical) are converted to the 'lowest' type which is character.

可以使用 [ 运算符查找向量中的元素。

vec_int <- c(1,2,3)
vec_char <- c('a','b','c')
vec_int[2] # accessing the second element will return 2
vec_char[2] # accessing the second element will return 'b'

这也可用于更改值

vec_int[2] <- 5 # change the second value from 2 to 5
vec_int # returns [1] 1 5 3

最后,:运算符(函数 seq() 的缩写)可用于快速创建数字向量。

vec_int <- 1:10
vec_int # returns [1] 1 2 3 4 5 6 7 8 9 10

这也可用于子集向量(从易于更复杂的子集)

vec_char <- c('a','b','c','d','e')
vec_char[2:4] # returns [1] "b" "c" "d"
vec_char[c(1,3,5)] # returns [1] "a" "c" "e"