How to modify the variable names by combining current variable names and row 1 values?

Viewed 53

How can I modify raw_dataframe to wished_dataframe?

raw_dataframe <- data.frame(
          category=c('a','1','2','3','4'),
          subcategory=c('b','3','2','1','0'),
          item=c('wd','4','5','7','0'))

wished_dataframe <- data.frame(
  category_a=c('1','2','3','4'),
  subcategory_b=c('3','2','1','0'),
  item_wd=c('4','5','7','0'))

I actually have many csv files, the structure like 'raw_dataframe ' and (I want to combine row 1 and row 2 as the variable name. Any one can help?

3 Answers
# Paste colnames with values of row 1
colnames(raw_dataframe) <- paste0(colnames(raw_dataframe), "_", raw_dataframe[1, ])

# Remove row 1 and save in `wished_dataframe`
wished_dataframe <- raw_dataframe[-1, ]

A dplyr way: We could use rename_with:

library(dplyr)
raw_dataframe %>% 
    rename_with(~paste0(.,"_", raw_dataframe[1,])) %>% 
    slice(-1)
  category_a subcategory_b item_wd
1          1             3       4
2          2             2       5
3          3             1       7
4          4             0       0

An option with janitor

library(janitor)
library(stringr)
library(dplyr)
row_to_names(raw_dataframe, 1) %>%
     rename_with(~ str_c(names(raw_dataframe), '_', .))
  category_a subcategory_b item_wd
2          1             3       4
3          2             2       5
4          3             1       7
5          4             0       0
Related