R Program to combines two given vectors by columns, rows


February 21, 2023, Learn eTutorial
1113

How to combine two given vectors by columns and rows using the R program?

For writing an R program that combines two given vectors by columns, and rows, we are using two built-in functions rbind() and cbind()

  • cbind() takes a sequence of vectors, matrix, or data frame as its arguments and combines it by columns.
  • rbind() takes a sequence of vectors, matrix, or data frame as its arguments and combines 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
  • deparse.level indicates any integer controlling the construction of labels in the case of non-matrix-like arguments.

In this R program, we directly give the values to combine. We are using two vectors into the variables v1 and v2 and variable results for holding combined vectors. First, we are displaying the original vector and then we combine it column-wise using the function cbind(v1,v2), and next time we combined it row-wise using rbind(v1,v2). Finally display the result

ALGORITHM

STEP 1: Assign variables v1 and v2 with vectors

STEP 2: Display the 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