How to add columns to an existing data frame in R
Overview
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.
How to add a column to a data frame
To add a column to an existing data frame, we use the cbind() function.
Syntax
cbind(data_frame, column_data)
Parameters
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.
Return value
The cbind() function returns a modified data frame with a new column.
Example 1
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
Explanation
- Lines 2 to 6: We create a data frame variable,
My_Data_frame, using thedata.frame()function. The data frame contains three columns. - Line 9: We use the
cbind()function to add a new column withnationalityas a name to the existing data frame. - Line 11: We print the new data frame
New_Data_Frame.
Example 2
# 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
Explanation
- Lines 2 to 5: We create a data frame variable,
My_Data_frame, using thedata.frame()function. The data frame contains three columns. - Line 9: We use the
cbind()function to add a new column withComplexionas a name to the existing data frame. - Line 11: We print the new data frame
New_Data_Frame.