
Ama N. answered 11/10/22
R Programmer | Data Scientist | Data Visualization Designer
Let's assume that you have a data frame called data_set that contains two columns, V1 and V2:
set.seed(0721) # use set.seed to replicate data set exactly
data_set <- data.frame(V1 = c("Variable 1", sample(c("apples", "grapes", "oranges"), size = 10, replace = TRUE)), V2 = c("Variable 2", sample(c("soccer", "basketball", "football"), size = 10, replace = TRUE)))
V1 contains information about the favorite fruit of several survey participants from three types (apples, grapes, and oranges), while V2 includes information on those same participants' favorite sport from a list of soccer, basketball, or football. Let's also assume that you want to rename the columns to something more meaningful, namely: fav_fruit and fav_sport:
names(data_set) <- c("fav_fruit", "fav_sport")
After renaming the columns, you notice that the first row of each column contains a variable label. Use the square bracket operator to remove these labels:
data_set2 <- data_set[-1, ]
A tidyverse solution using rename and slice from dplyr would be:
library(tidyverse) # load tidyverse
data_set2 <- data_set %>%
rename(fav_fruit = V1, fav_sport = V2) %>% # rename the columns
slice(-1) # remove the first row