Here we are explaining how to write an R program that combines two given vectors by columns, rows. For this, we are using two built-in functions rbind() and cbind(). The function cbind() takes a sequence of vector, matrix, or data frame as its arguments and combines it by columns, and the function rbind() takes a sequence of vector, matrix, or data frame as its arguments and combine it by rows. Both of these have the following syntax,
Where dots(….) indicates any vectors or matrices and deparse.level indicates any integer controlling the construction of labels in the case of non-matrix-like arguments.
Below are the steps used in the R program to combines two given vectors by columns, rows. In this R program, we directly give the values to combine. For this here we are using two vectors into the variables v1 and v2 and variable result for holding combined vectors. At first, we combine it column-wise using the function cbind(v1,v2), and next time we combined it row-wise using rbind(v1,v2).
v1 = c(4,5,6,7,8)
v2 = c(1,2,3,4,5)
print("Original vectors:")
## [1] "Original vectors:"
print(v1)
## [1] 4 5 6 7 8
print(v2)
## [1] 1 2 3 4 5
print("Combines the vectors by columns:")
## [1] "Combines the vectors by columns:"
result = cbind(v1,v2)
print(result)
## v1 v2
## [1,] 4 1
## [2,] 5 2
## [3,] 6 3
## [4,] 7 4
## [5,] 8 5
print("Combines the vectors by rows:")
## [1] "Combines the vectors by rows:"
result = rbind(v1,v2)
print(result)
## [,1] [,2] [,3] [,4] [,5]
## v1 4 5 6 7 8
## v2 1 2 3 4 5
v1 = c(40,50,60,70,80)
v2 = c(10,20,30,40,50)
print("Original vectors:")
## [1] "Original vectors:"
print(v1)
## [1] 40 50 60 70 80
print(v2)
## [1] 10 20 30 40 50
print("Combines the vectors by columns:")
## [1] "Combines the vectors by columns:"
result = cbind(v1,v2)
print(result)
## v1 v2
## [1,] 40 10
## [2,] 50 20
## [3,] 60 30
## [4,] 70 40
## [5,] 80 50
print("Combines the vectors by rows:")
## [1] "Combines the vectors by rows:"
result = rbind(v1,v2)
print(result)
## [,1] [,2] [,3] [,4] [,5]
## v1 40 50 60 70 80
## v2 10 20 30 40 50