The cbind, short for column bind in R, is a function “used to combine specified Vector, Matrix or Data Frame by columns”.
Syntax
cbind(a1, a2, ..., deparse.level = 1)
Parameters
- a1, a2: It is a vector, matrix, and data frame.
- deparse.level: This value determines how the column names are generated. The default value of the deparse.level is 1.
Example 1: cbind Vector to Data Frame
You can bind a vector to a data frame using the “cbind()” function.
x <- c("a", "b", "c")
y <- c(1, 2, 3)
df <- data.frame(x = x, y = y)
z <- c("d", "e", "f")
df <- cbind(df, z)
print(df)
Output
x y z
1 a 1 d
2 b 2 e
3 c 3 f
Example 2: Combine two data frames using cbind()
To combine two data frames by columns, use the “cbind()” function.
df <- data.frame(c1 = c(1, 2, 3, 4),
c2 = c(5, 6, 7, 8),
c3 = c(9, 10, 11, 12))
df
df2 <- data.frame(c4 = c(18, 19, 20, 21),
c5 = c(29, 46, 47, 37))
df2
cat("After adding another data frame using cbind()", "\n")
newDf <- cbind(df, df2)
newDf
Output
c1 c2 c3
1 1 5 9
2 2 6 10
3 3 7 11
4 4 8 12
c4 c5
1 18 29
2 19 46
3 20 47
4 21 37
After adding another data frame using cbind()
c1 c2 c3 c4 c5
1 1 5 9 18 29
2 2 6 10 19 46
3 3 7 11 20 47
4 4 8 12 21 37
Example 3: cbind Multiple Columns
The cbind() function can also be applied to multiple columns and data objects. For example, define a data frame using three columns, and add two columns to that data frame using the cbind() function.
df <- data.frame(c1 = c(1, 2, 3, 4),
c2 = c(5, 6, 7, 8),
c3 = c(9, 10, 11, 12))
c4 <- c(18, 19, 20, 21)
c5 <- c(29, 46, 47, 37)
cat("After adding multiple columns using cbind()", "\n")
newDf <- cbind(df, c4, c5)
newDf
Output
After adding multiple columns using cbind()
c1 c2 c3 c4 c5
1 1 5 9 18 29
2 2 6 10 19 46
3 3 7 11 20 47
4 4 8 12 21 37
Example 4: Cbind Vectors into a Matrix
To combine vectors into the matrix in R, you can use the “cbind()” function.
a <- c(1, 2, 3)
b <- c(4, 5, 6)
mat <- cbind(a, b)
d <- c(7, 8, 9)
matrx <- cbind(mat, d)
print(matrx)
Output
a b d
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
That’s all!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.