将数据框行转换为列名

Convert data frame row to column names

有没有一种快速的方法(可能是 tidyverse API 的一部分)将行转换为 data.frametibble 的列名称,有点类似于tibble::column_to_rownames?

我知道有很多方法可以做到这一点,例如有点笨拙:

> df <- head(iris)
> 
> df %>%
+     set_colnames(magrittr::extract(., 1,)) %>%
+     magrittr::extract(-1,)
  5.1 3.5 1.4 0.2      1
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

嗯,你可以简单地:colnames(df) <- as.character(df[1, ])

如果您想删除第一行:df <- df[-1,]

janitor::row_to_names() 实现了这个:

library(tidyverse)

iris %>%
  head() %>%
  janitor::row_to_names(1)
#>   5.1 3.5 1.4 0.2      1
#> 2 4.9 3.0 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5.0 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa

reprex package (v0.2.1)

于 2019-05-29 创建