How to add columns to a data frame in R
How to add columns to a data frame in R?, To add one or more columns to a data frame in R, use the mutate() function from the dplyr package.
With the following data frame, the following examples demonstrate how to use this syntax in practice.
How to add labels at the end of each line in ggplot2? (datasciencetut.com)
How to add columns to a data frame in R
Let’s create a data frame
df <- data.frame(player = c('P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7'), points = c(122, 144, 154, 155, 120, 218, 229), assists = c(43, 55, 77, 18, 114, NA,29))
Now we can view the data frame
df
player points assists 1 P1 122 43 2 P2 144 55 3 P3 154 77 4 P4 155 18 5 P5 120 114 6 P6 218 NA 7 P7 229 29
Approach 1: Add Column at End of Data Frame
The following code demonstrates how to add a column to the data frame’s end.
Two Sample Proportions test in R-Complete Guide – Data Science Tutorials
at the end of the data frame, add a ‘blocks’ column
df <- df %>% mutate(score=c(1, 3, 3, 2, 4, 3, 6))
Let’s view the data frame
df
player points assists score 1 P1 122 43 1 2 P2 144 55 3 3 P3 154 77 3 4 P4 155 18 2 5 P5 120 114 4 6 P6 218 NA 3 7 P7 229 29 6
It’s worth noting that you may create an empty column by just giving NA to each of the new column’s values.
Dealing With Missing values in R – Data Science Tutorials
at the conclusion of the data frame, add an empty column
df <- df %>% mutate(blocks=NA)
df
player points assists score 1 P1 122 43 NA 2 P2 144 55 NA 3 P3 154 77 NA 4 P4 155 18 NA 5 P5 120 114 NA 6 P6 218 NA NA 7 P7 229 29 NA
Approach 2: Add Column Before Specific Column
The following code demonstrates how to insert a column in front of a certain column in a data frame:
insert the ‘score’ column after the ‘points’ column.
df <- df %>% mutate(score=c(1, 3, 3, 2, 4, 3, 6), .before=points)
df
player points assists score 1 P1 122 43 1 2 P2 144 55 3 3 P3 154 77 3 4 P4 155 18 2 5 P5 120 114 4 6 P6 218 NA 3 7 P7 229 29 6
Approach 3: Add Column After Specific Column
The following code demonstrates how to add a column to the data frame after a certain column.
How to Remove Columns from a data frame in R – Data Science Tutorials
Following the ‘points’ column, add a ‘score’ column
df <- df %>% mutate(blocks=c(1, 3, 3, 2, 4, 3, 6), .after=points) df
player points blocks assists score 1 P1 122 1 43 1 2 P2 144 3 55 3 3 P3 154 3 77 3 4 P4 155 2 18 2 5 P5 120 4 114 4 6 P6 218 3 NA 3 7 P7 229 6 29 6
Approach 4: Add Column Based on Other Columns
The following code demonstrates how to add a column in a data frame based on another column.
Best GGPlot Themes You Should Know – Data Science Tutorials
add a ‘status’ column whose values are based on the ‘points’ column’s value
df <- df %>% mutate(status= if_else(.$points > 20, 'Good', 'Bad')) df
player points blocks assists score status 1 P1 122 1 43 1 Good 2 P2 144 3 55 3 Good 3 P3 154 3 77 3 Good 4 P4 155 2 18 2 Good 5 P5 120 4 114 4 Good 6 P6 218 3 NA 3 Good 7 P7 229 6 29 6 Good