要编写一个 R 程序,将两个给定向量按列和行组合,我们使用两个内置函数 **rbind()** 和 **cbind()**。
这两个函数都有以下语法:
cbind(…, deparse.level = 1)
rbind(…, deparse.level = 1)
其中
在此 R 程序中,我们直接给出要组合的值。我们将两个向量赋给变量 **v1** 和 **v2**,并使用变量 results 来保存组合后的向量。首先,我们显示原始向量,然后使用函数 **cbind(v1,v2)** 按列组合它们,接着使用 **rbind(v1,v2)** 按行组合它们。最后显示结果。
**步骤 1**:为变量 **v1 和 v2** 赋值向量
**步骤 2**:显示原始向量值
**步骤 3**:通过调用 **cbind(v1,v2)** 按列组合向量
**步骤 4**:打印**结果**向量
**步骤 5**:通过调用 **rbind(v1,v2)** 按行组合向量
**步骤 6**:打印**结果**向量
v1 = c(4,5,6,7,8)
v2 = c(1,2,3,4,5)
print("Original vectors:")
print(v1)
print(v2)
print("Combines the vectors by columns:")
result = cbind(v1,v2)
print(result)
print("Combines the vectors by rows:")
result = rbind(v1,v2)
print(result)
[1] "Original vectors:"
[1] 4 5 6 7 8
[1] 1 2 3 4 5
[1] "Combines the vectors by columns:"
v1 v2
[1,] 4 1
[2,] 5 2
[3,] 6 3
[4,] 7 4
[5,] 8 5
[1] "Combines the vectors by rows:"
[,1] [,2] [,3] [,4] [,5]
v1 4 5 6 7 8
v2 1 2 3 4 5