R 向量


向量

向量只是相同类型的项目的列表。

要将项目列表合并为向量,请使用c()函数并用逗号分隔项目。

在下面的示例中,我们创建一个名为的向量变量水果,组合字符串:

示例

# 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)
亲自试一试 »


对向量进行排序

要按字母或数字顺序对向量中的项目进行排序,请使用sort()功能:

示例

fruits <- c("banana", "apple", "orange", "mango", "lemon")
numbers <- c(13, 3, 5, 7, 20, 2)

sort(fruits)  # Sort a string
sort(numbers) # Sort numbers
亲自试一试 »

访问向量

您可以通过引用括号内的索引号来访问向量项[]。第一项的索引为 1,第二项的索引为 2,依此类推:

示例

fruits <- c("banana", "apple", "orange")

# Access the first item (banana)
fruits[1]
亲自试一试 »

您还可以通过使用不同的索引位置来访问多个元素c()功能:

示例

fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Access the first and third item (banana and orange)
fruits[c(1, 3)]
亲自试一试 »

您还可以使用负索引号来访问除指定项目之外的所有项目:

示例

fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Access all items except for the first item
fruits[c(-1)]
亲自试一试 »

更改项目

要更改特定项目的值,请参阅索引号:

示例

fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Change "banana" to "pear"
fruits[1] <- "pear"

# Print fruits
fruits
亲自试一试 »

重复向量

要重复向量,请使用rep()功能:

示例

重复每个值:

repeat_each <- rep(c(1,2,3), each = 3)

repeat_each
亲自试一试 »

示例

重复向量的序列:

repeat_times <- rep(c(1,2,3), times = 3)

repeat_times
亲自试一试 »

示例

独立重复每个值:

repeat_indepent <- rep(c(1,2,3), times = c(5,2,1))

repeat_indepent
亲自试一试 »

生成测序向量

上面的示例之一向您展示了如何使用序列中的数值创建一个向量:运算符:

示例

numbers <- 1:10

numbers
亲自试一试 »

要按顺序进行更大或更小的步骤,请使用seq()功能:

示例

numbers <- seq(from = 0, to = 100, by = 20)

numbers
亲自试一试 »

笔记:这个seq()函数有三个参数:from是序列开始的地方,to是序列停止的地方,并且by是序列的间隔。