Here are two ways to add a new column to a DataFrame in R:
(1) Using the $ symbol:
df$new_column_name <- c("value_1", "value_2", "value_3", ...)
(2) Using cbind:
df <- cbind(df, new_column_name = c("value_1", "value_2", "value_3", ...))
Examples of Adding a New Column to a DataFrame in R
Example 1: Add a new column using the $ symbol
To start, create a DataFrame with two columns called “Colors” and “Shapes“:
df <- data.frame(Colors = c("red", "green", "blue", "yellow", "orange"),
Shapes = c("square", "circle", "triangle", "rectangle", "cone")
)
print(df)
Here is the DataFrame with the 2 columns:
Colors Shapes
1 red square
2 green circle
3 blue triangle
4 yellow rectangle
5 orange cone
Now add a third column, called the “Sizes” column, to the DataFrame:
df <- data.frame(Colors = c("red", "green", "blue", "yellow", "orange"),
Shapes = c("square", "circle", "triangle", "rectangle", "cone")
)
df$Sizes <- c("small", "medium", "large", "small", "medium")
print(df)
The “Sizes” column will be added at the end of the DataFrame:
Colors Shapes Sizes
1 red square small
2 green circle medium
3 blue triangle large
4 yellow rectangle small
5 orange cone medium
Example 2: Add a new column using cbind
To add the same “Sizes” column using cbind:
df <- data.frame(Colors = c("red", "green", "blue", "yellow", "orange"),
Shapes = c("square", "circle", "triangle", "rectangle", "cone")
)
df <- cbind(df, Sizes = c("small", "medium", "large", "small", "medium"))
print(df)
As before, the “Sizes” column will be added at the end of the DataFrame:
Colors Shapes Sizes
1 red square small
2 green circle medium
3 blue triangle large
4 yellow rectangle small
5 orange cone medium