Suppose we have the following dataset
1 2 3 4 5 6 7 8 9 |
##### Creating Sample Data ##### Name <- as.character(c("Abbey", "Brian", "Connie", "Dan", "Ethan")) GPA <- c(3.0, 2.8, 2.1, 4.0, NA) Grade <- c(3, 4, NA, NA, 6) State <- c("AL", NA, NA, NA, "CA") data <- data.frame(Name, GPA, Grade, State, stringsAsFactors = FALSE) data |
1 2 3 4 5 6 7 |
> data Name GPA Grade State 1 Abbey 3.0 3 AL 2 Brian 2.8 4 <NA> 3 Connie 2.1 NA <NA> 4 Dan 4.0 NA <NA> 5 Ethan NA 6 CA |
For whatever reason, we want to change the column names to a, b, c, and d. There are many ways to accomplish the task.Using mutate() to create new variables works. But using colnames() is way easier.
1 2 3 4 |
#### Colnames() ##### colnames(data) <- c('x','b','a','d') data |
1 2 3 4 5 6 7 |
> data x b a d 1 Abbey 3.0 3 AL 2 Brian 2.8 4 <NA> 3 Connie 2.1 NA <NA> 4 Dan 4.0 NA <NA> 5 Ethan NA 6 CA |