2

I have a dataframe, df :

df <- structure(list(V1 = c("H1", " 0.9", 
"4.1", "4.0"), V2 = c("H2", " 2.174", 
"4.1", "4.1"), V3 = c("H3", " 2.592", 
"3.8", "4.1"), V4 = c("H4", " 2.236", 
"3.8", "4.087463")), row.names = c(NA, -4L), class = "data.frame")

> df
    V1     V2     V3     V4
1   H1     H2     H3     H4
2  0.9  2.174  2.592  2.236
3  4.1    4.1    3.8    3.8
4  4.0    4.1    4.1    4.0

I would like to rename the columns after the first row, but using a dplyr pipe.

The desired outcome would look like:

    H1     H2     H3     H4
2  0.9  2.174  2.592  2.236
3  4.1    4.1    3.8    3.8
4  4.0    4.1    4.1    4.0

I have tried this but it doesn't work:

df_new <- df %>%
    rename_all(.,df[1,])

Can someone suggest a tidy method to do this using dplyr?

icedcoffee
  • 935
  • 1
  • 6
  • 18
  • Related pre-pipe answer: [How to change the first row to be the header in R?](https://stackoverflow.com/questions/23209330/how-to-change-the-first-row-to-be-the-header-in-r) – Henrik Aug 19 '20 at 20:37

2 Answers2

3

We can use row_to_names from janitor

library(janitor)
library(dplyr)
df %>%
    row_to_names(row_number = 1) %>%
    type.convert(as.is = TRUE) %>%
    as_tibble
# A tibble: 3 x 4
#     H1    H2    H3    H4
#  <dbl> <dbl> <dbl> <dbl>
#1   0.9  2.17  2.59  2.24
#2   4.1  4.1   3.8   3.8 
#3   4    4.1   4.1   4.09
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Not fully piped but without extra package :

library(dplyr)

colnames(df)<-df[1,]
df %>% tail(-1)
    H1     H2     H3       H4
2  0.9  2.174  2.592    2.236
3  4.1    4.1    3.8      3.8
4  4.0    4.1    4.1 4.087463

Or fully piped as suggested by @IceCreamToucan & @Henrik:

df %>% setNames(.[1,]) %>% tail(-1) %>% mutate(across(everything(),as.numeric))
   H1    H2    H3       H4
1 0.9 2.174 2.592 2.236000
2 4.1 4.100 3.800 3.800000
3 4.0 4.100 4.100 4.087463
Waldi
  • 39,242
  • 6
  • 30
  • 78