cbind in R: How to Column Bind Objects

cbind in R tutorial with examples

The cbind() function in R allows you to combine one or more vectors, matrices, or data frames by columns.

The following graphic shows how cbind() can combine two data frames by columns:

Note: cbind() only works if each data frame has the same number of rows.

The complete documentation for cbind() can be found here.

The following examples illustrate practical examples of using cbind().

Using cbind to Combine Data Frames by Columns

One of the most common uses of cbind() is to combine data frames by columns. The following example shows how to combine two data frames using cbind().

#create a data frame with two columns and four rows
data1 <- data.frame(A = c(1, 3, 7, 8), B = c(4, 2, 5, 9))
data1

#  A B
#1 1 4
#2 3 2
#3 7 5
#4 8 9

#create another data frame with two columns and four rows
data2 <- data.frame(C = c(9, 2, 4, 8), D = c(12, 12, 15, 4))
data2

#  C D
#1 9 12
#2 2 12
#3 4 15
#4 8 4

#combine the two data frames into one new data frame
new_data <- cbind(data1, data2)
new_data

#  A B C D
#1 1 4 9 12
#2 3 2 2 12
#3 7 5 4 15
#4 8 9 8 4

We can also use cbind() to combine more than two data frames:

#create three data frames, each with two columns and four rows
data1 <- data.frame(A = c(1, 3, 7, 8), B = c(4, 2, 5, 9))
data2 <- data.frame(C = c(9, 2, 4, 8), D = c(12, 12, 15, 4))
data3 <- data.frame(E = c(24, 23, 5, 6), F = c(7, 8, 1, 2))

#cbind the three data frames together into one new data frame
new_data <- cbind(data1, data2, data3)
new_data

#  A B C  D  E F
#1 1 4 9 12 24 7
#2 3 2 2 12 23 8
#3 7 5 4 15  5 1
#4 8 9 8  4  6 2

Note that cbind() only works if each of the data frames have the same number of rows.

Using cbind to Combine Vectors into a Matrix or Data Frame

Another common use of cbind() is to column bind one or more vectors into a matrix or data frame.

The following code shows how to cbind() two vectors into a matrix:

#create two vectors, both of length four
a <- c(4, 5, 12, 16)
b <- c(9, 3, 2, 1)

#cbind the two vectors into a matrix
new_data <- cbind(a, b)
new_data
class(new_data)

#      a b
#[1,]  4 9
#[2,]  5 3
#[3,] 12 2
#[4,] 16 1

#[1] "matrix"

In order to cbind() two or more vectors into a data frame, we can simply add as.data.frame like below:

#create two vectors, both of length four
a <- c(4, 5, 12, 16)
b <- c(9, 3, 2, 1)

#cbind the two vectors into a data frame
new_data <- as.data.frame(cbind(a, b))
new_data
class(new_data)

#   a b
#1  4 9
#2  5 3
#3 12 2
#4 16 1

#[1] "data.frame"

Note that the names of the columns in the new data frame are simply the names of the vectors. Find out how to change the names of columns here.

Leave a Reply

Your email address will not be published. Required fields are marked *