在 R 编程中对向量进行附加操作
R编程中的向量是由同质元素序列组成的基本对象。它可以是整数、逻辑、双精度、字符、复杂或原始。在本文中,让我们讨论在 R 编程中将值连接/附加到向量的不同方法。可以使用 2 种方法将值附加/连接到向量中:
- c()函数
- 附加()函数
使用 c()函数追加操作
c()函数是将数据组合成向量或列表的通用函数。
Syntax: c(…)
Parameters:
…: represents objects to be concatenated
要了解更多可选参数,请在控制台中使用以下命令:
help("c")
示例 1:
r
# Create a vector
x <- 1:5
n <- 6:10
# Append using c() function
y <- c(x, n)
# Print resultant vector
print(y)
r
# Create vector
x <- 1:5
n <- letters[1:5]
# Append
y <- c(x, n)
# Print resultant vector
print(y)
# Print type of resultant vector
typeof(y)
# Print type of other vectors
typeof(x)
typeof(n)
r
# Create a vector
x <- 1:5
# Append using append() function
x <- append(x, 6:10)
# Print resultant vector
print(x)
r
# Create a vector
x <- 1:5
y <- letters[1:5]
# Append using append() function
x <- append(x, values = y)
# Print resultant vector
print(x)
输出:
[1] 1 2 3 4 5 6 7 8 9 10
示例 2:
r
# Create vector
x <- 1:5
n <- letters[1:5]
# Append
y <- c(x, n)
# Print resultant vector
print(y)
# Print type of resultant vector
typeof(y)
# Print type of other vectors
typeof(x)
typeof(n)
输出:
[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"
[1] "character"
[1] "integer"
[1] "character"
使用 append()函数追加操作
R 中的append()函数用于合并向量或向向量添加更多元素。
Syntax: append(x, values)
Parameters:
x: represents a vector to which values has to be appended to
values: represents the values which has to be appended in the vector
示例 1:
r
# Create a vector
x <- 1:5
# Append using append() function
x <- append(x, 6:10)
# Print resultant vector
print(x)
输出:
[1] 1 2 3 4 5 6 7 8 9 10
示例 2:
r
# Create a vector
x <- 1:5
y <- letters[1:5]
# Append using append() function
x <- append(x, values = y)
# Print resultant vector
print(x)
输出:
[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"