Hand holding pencil reviewing colorful data charts on desk with laptop.

How you can Virtue cbind in R (With Examples)

Posted on
banner 336x280

The cbind serve as in R, trim for column-bind, will also be impaired to mix vectors, matrices and information frames by way of column.

Refer to examples display the way to worth this serve as in follow.

banner 468x60

Instance 1: Cbind Vectors right into a Matrix

Refer to code presentations the way to worth cbind to column-bind two vectors right into a unmarried matrix:

#develop two vectors
a <- c(1, 3, 3, 4, 5)
b <- c(7, 7, 8, 3, 2)

#cbind the 2 vectors right into a matrix
new_matrix <- cbind(a, b)

#view matrix
new_matrix

     a b
[1,] 1 7
[2,] 3 7
[3,] 3 8
[4,] 4 3
[5,] 5 2

#view elegance of new_matrix
elegance(new_matrix)

[1] "matrix" "array" 

Instance 2: Cbind Vector to a Knowledge Body

Refer to code presentations the way to worth cbind to column-bind a vector to an present knowledge body:

#develop knowledge body
df <- knowledge.body(a=c(1, 3, 3, 4, 5),
                 b=c(7, 7, 8, 3, 2),
                 c=c(3, 3, 6, 6, 8))

#outline vector
d <- c(11, 14, 16, 17, 22)

#cbind vector to knowledge body
df_new <- cbind(df, d)

#view knowledge body
df_new

  a b c  d
1 1 7 3 11
2 3 7 3 14
3 3 8 6 16
4 4 3 6 17
5 5 2 8 22

Be aware that R will throw an error if the field of the vector isn’t the similar because the field of the columns within the present knowledge body.

Instance 3: Cbind A couple of Vectors to a Knowledge Body

Refer to code presentations the way to worth cbind to column-bind a couple of vectors to an present knowledge body:

#develop knowledge body
df <- knowledge.body(a=c(1, 3, 3, 4, 5),
                 b=c(7, 7, 8, 3, 2),
                 c=c(3, 3, 6, 6, 8))

#outline vectors
d <- c(11, 14, 16, 17, 22)

e <- c(34, 35, 36, 36, 40) 

#cbind vectors to knowledge body
df_new <- cbind(df, d, e)

#view knowledge body
df_new

  a b c  d  e
1 1 7 3 11 34
2 3 7 3 14 35
3 3 8 6 16 36
4 4 3 6 17 36
5 5 2 8 22 40

Instance 4: Cbind Two Knowledge Frames

Refer to code presentations the way to worth cbind to column-bind two knowledge frames into one knowledge body:

#develop two knowledge frames
df1 <- knowledge.body(a=c(1, 3, 3, 4, 5),
                  b=c(7, 7, 8, 3, 2),
                  c=c(3, 3, 6, 6, 8))

df2 <- knowledge.body(d=c(11, 14, 16, 17, 22),
                  e=c(34, 35, 36, 36, 40))

#cbind two knowledge frames into one knowledge body
df_new <- cbind(df1, df2)

#view knowledge body
df_new

  a b c  d  e
1 1 7 3 11 34
2 3 7 3 14 35
3 3 8 6 16 36
4 4 3 6 17 36
5 5 2 8 22 40

Bonus: If you wish to store in combination vectors, matrices, or knowledge frames by way of rows, you’ll impaired the rbind serve as in lieu.

banner 336x280

Leave a Reply

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