R Program to combines two given vectors by columns, rows

How to combines two given vectors by columns, rows

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,

cbind(…, deparse.level = 1)
rbind(…, deparse.level = 1)
 
 

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.

How to combines two given vectors by columns, rows using the R program

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).

ALGORITHM

STEP 1: Assign variables v1 and v2 with vector values

STEP 2: First print original vector values

STEP 3: combine vectors column-wise by calling cbind(v1,v2)

STEP 4: print the result vector

STEP 5: combine vectors row-wise by calling rbind(v1,v2)

STEP 6: print the result vector

R Source Code

                                          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)
                                      

OUTPUT

[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