#-----------------------------------------------------------------------------# cbind and rbind functions## cbind combines (i.e. "binds") columns from multiple dataframes, matrices and vectors.# rbind combines (i.e. "binds") columns from multiple dataframes, matrices and vectors.## For both cbind and rbind# - If all items being "bound" are vectors and matrices then the result is a matrix.# - If any of the items being "bound" is a dataframe, the result is a dataframe.#-----------------------------------------------------------------------------#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>># Use cbind to vectors into a matrix#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ones =c(1,2,3,4,5)tens =c(10,20,30,40,50)hundreds =c(100,200,300,400,500)nums =cbind(ones, tens, hundreds) # a matrix with 3 columnsclass(nums) # "matrix" "array"
[1] "matrix" "array"
# add another column to the matrixnums =cbind(nums, thousands =c(1000,2000,3000,4000,5000))nums
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>># Use cbind to combine columns from different# dataframes and vectors into one dataframe#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>># A few rowsdf1 =data.frame ( students =c("alice", "bob", "carla"),# year = factor( c("junior", "freshman", "junior"),# levels = c("freshman", "sophomore", "junior", "senior"),# ordered = TRUE),test1 =c(71, 81, 91),stringsAsFactors =FALSE)df1
students test1
1 alice 71
2 bob 81
3 carla 91
# two more testsdf2 =data.frame ( test2 =c(72, 82, 92),test3 =c(73, 83, 93),test4 =c(74, 84, 94) )df2
# You can also use cbind to combine a vectors# The result is a matrixmat =cbind (x =c(1,2,3), y=c(100,200,300), z=c(111, 222, 333))mat
x y z
[1,] 1 100 111
[2,] 2 200 222
[3,] 3 300 333
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>># Use rbind to combine rows from different dataframes#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>># A few more rowsdf3 =data.frame ( students =c("david", "ed", "fran"),# year = factor( c("junior", "freshman", "junior"),# levels = c("freshman", "sophomore", "junior", "senior"),# ordered = TRUE),test1 =c(75, 85, 95),stringsAsFactors =FALSE)df2
# Use "rbind" to combine the rows from df1 with the rows from df2 into a# single data.frame.## The "r" in "rbind" stands for "row" since we are "binding the rows together")allRows =rbind(df1, df2)
Error in rbind(deparse.level, ...): numbers of columns of arguments do not match
allRows
Error in eval(expr, envir, enclos): object 'allRows' not found
x =rbind(allRows, c("a","b","c"))
Error in eval(expr, envir, enclos): object 'allRows' not found
str(x)
Error in eval(expr, envir, enclos): object 'x' not found