How to add a column to a data frame in the R language?
In R language, there are several methods that can be used to add columns to a data frame.
- Add a column using the “$” operator.
dataframe$new_column <- values
In this case, dataframe is the name of the data frame, new_column is the name of the column to be added, and values are the values to be added to the column. This method can be used to directly add a new column to the data frame with the corresponding values.
- Add columns using an index.
dataframe[, "new_column"] <- values
Similarly, dataframe refers to the name of the data frame, new_column is the name of the column to be added, and values are the values to be added to the column. This method uses the index to add a new column to the data frame and assigns the corresponding values.
- change its form
library(dplyr)
dataframe <- dataframe %>% mutate(new_column = values)
Firstly, load the dplyr package and then use the mutate() function to add a column. The dataframe is the name of the data frame, new_column is the name of the column to be added, and values are the values to be added to the column. This method allows for adding a new column to the data frame with the corresponding values.
It is important to note that the values in the above methods can be a specific value or a vector, with a length matching the number of rows in the data frame.