assign headers based on existing row in dataframe in R

后端 未结 5 647
谎友^
谎友^ 2020-12-12 19:31

After transforming a dataframe, I would like to assign heads/names to the columns based on an existing row. My headers are currently:

5条回答
  •  猫巷女王i
    2020-12-12 19:37

    A new answer that uses dplyr and tidyr:

    Extracts the desired column names and converts to a list

    library(tidyverse)
    
    col_names <- raw_dta %>% 
      slice(2) %>%
      pivot_longer(
        cols = "X2":"X10", # until last named column
        names_to = "old_names",
        values_to = "new_names") %>% 
      pull(new_names)
    

    Removes the incorrect rows and adds the correct column names

    dta <- raw_dta %>% 
      slice(-1, -2) %>% # Removes the rows containing new and original names
      set_names(., nm = col_names)
    
    

提交回复
热议问题