3.1 Vectors

👉 Vector in R = 1d-array in Python@Numpy

3.1.1 Initialization (初始化)

c(2,3,4)        # [1] 2 3 4
2:4             # [1] 2 3 4
numeric(3)      # [1] 0 0 0
  1. c()
  2. 2:5返回由从2到5的整数组成的向量
  3. numeric(10)初始化一个长度为10的zero vector

⚠️ 和Python不同的是,R不是嵌套vector!

>>> c(c(1,2), c(3,4))
[1] 1 2 3 4

如果是python,则结果是[[1,2], [3,4]]而不是[1,2,3,4]

3.1.2 Index (索引)

You can give a name to the elements of a vector with the names() function.

>>> poker_vector <- c(140, -50, 20, -120, 240)
>>> poker_vector
[1]  140  -50   20 -120  240

>>> names(poker_vector) <- c("Mon", "Tue", "Wed", "Thu", "Fri")
>>> poker_vector
Mon  Tue  Wed  Thu  Fri
140  -50   20 -120  240

>>> poker_vector[1]
Mon
140

>>> poker_vector[c(1,5)]
Mon Fri
140 240

>>> poker_vector[1:3]
Mon Tue Wed
140 -50  20

>>> poker_vector[c("Mon","Fri")]
Mon Fri
140 240

>>> poker_vector[c(TRUE, FALSE, TRUE, FALSE, FALSE)]
Mon Wed
140  20

>>> length(poker_vector)
[1] 5
  1. 可以使用默认的数字索引来选择vector中的element:和python不同,R是从1开始
  2. 要选择vector中的多个elements,括号里放索引的vector
  3. 要选择vector中的连续elements,可以和python一样用冒号,但是注意「前闭后闭
  4. 可以使用vector中element的name来选择元素