向量只是相同类型的项目的列表。
要将项目列表合并为向量,请使用c()
函数并用逗号分隔项目。
在下面的示例中,我们创建一个名为的向量变量水果,组合字符串:
在此示例中,我们创建一个组合数值的向量:
要创建具有序列中数值的向量,请使用:
运算符:
您还可以在序列中创建带小数的数值,但请注意,如果最后一个元素不属于序列,则不会使用它:
# 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
在下面的示例中,我们创建一个逻辑值向量:
要找出向量有多少个项目,请使用length()
功能:
要按字母或数字顺序对向量中的项目进行排序,请使用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,依此类推:
您还可以通过使用不同的索引位置来访问多个元素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()
功能:
上面的示例之一向您展示了如何使用序列中的数值创建一个向量:
运算符:
要按顺序进行更大或更小的步骤,请使用seq()
功能:
笔记:这个seq()
函数有三个参数:from
是序列开始的地方,to
是序列停止的地方,并且by
是序列的间隔。
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!