R 语言 - 向量
在 R 语言中,向量(vector)只是相同类型的项目列表。
要将项目列表组合成向量,请使用 c()
函数并用逗号分隔项目。
创建向量
在下面的示例中,我们创建了一个名为 fruits 的向量变量,它是一系列字符串的组合。
# Vector of strings
fruits <- c("banana", "apple", "orange")
# Print fruits
fruits
在下面示例中,我们创建了一个组合数值的向量:
# Vector of numerical values
numbers <- c(1, 2, 3)
# Print numbers
numbers
要创建一个包含序列中数值的向量,请使用 :
运算符:
# Vector with numerical values in a sequence
numbers <- 1:10
numbers
你还可以在序列 中创建带小数的数值,但请注意,如果最后一个元素不属于该序列,则不会使用它:
# Vector with numerical decimals in a sequence
numbers1 <- 1.5:6.5
numbers1
# Vector with numerical decimals in a sequence where the last element is not used
numbers2 <- 1.5:6.3
numbers2
结果为
[1] 1.5 2.5 3.5 4.5 5.5 6.5
[1] 1.5 2.5 3.5 4.5 5.5
在下面的示例中,我们创建了一个逻辑值向量:
# Vector of logical values
log_values <- c(TRUE, FALSE, TRUE, FALSE)
log_values
向量长度
要找出一个向量有多少项,请使用 length()
函数:
fruits <- c("banana", "apple", "orange")
length(fruits)