Add Column in R: dplyr & Base R Methods
In R language, there are several methods available to add a column of data.
- The mutate() function in the dplyr package allows you to add new columns to a data frame. For example, if you have a data frame named df, you can use the following code to add a new column called new_col:
library(dplyr)
df <- mutate(df, new_col = c(1, 2, 3, 4, 5))
- You can directly add a new column to a data frame using the $ symbol. For example, if you have a data frame named df, you can use the following code to add a new column named new_col:
df$new_col <- c(1, 2, 3, 4, 5)
- The cbind() function can be used to add new columns to a data frame. For example, if we have a data frame named df, we can use the following code to add a column named new_col:
df <- cbind(df, new_col = c(1, 2, 3, 4, 5))
You can successfully add a new column to the data frame using any method.