In this shot, we’ll learn to add a column to an existing data frame. The data frame in R represents data in a table format with rows and columns.
To add a column to an existing data frame, we use the cbind()
function.
cbind(data_frame, column_data)
The cbind()
function takes the following parameter values:
data_frame
: Represents the data frame object.column_data
: Represents the column data we wish to add to the data frame.The cbind()
function returns a modified data frame with a new column.
The code below demonstrates the use of the cbind()
function:
# creating a data frameMy_Data_Frame <- data.frame (Height = c("Tall", "Average", "short"),Body_structure = c("Meso", "Endo", "Ecto"),Age = c(35, 30, 45))# adding a new columnNew_Data_Frame <- cbind(My_Data_Frame, nationality = c("Americam", "South African", "Italian"))New_Data_Frame
My_Data_frame
, using the data.frame()
function. The data frame contains three columns.cbind()
function to add a new column with nationality
as a name to the existing data frame.New_Data_Frame
.# creating a data frameMy_Data_Frame <- data.frame (Height = c("Tall", "Average", "short"),Body_structure = c("Meso", "Endo", "Ecto"),Age = c(35, 30, 45))# adding a new columnNew_Data_Frame <- cbind(My_Data_Frame, Complexion = c("Yellow", "Chocolate", "Dark"))New_Data_Frame
My_Data_frame
, using the data.frame()
function. The data frame contains three columns.cbind()
function to add a new column with Complexion
as a name to the existing data frame.New_Data_Frame
.