如何将数据框中的列转换为行名称

时间:2018-05-28 07:47:53

标签: r dataframe dplyr tidyverse

我有以下数据框:

library(tidyverse)
df <- structure(list(Peakid = c("chr1_3119849_3120205", "chr1_3164889_3165097", 
"chr1_3360993_3361240", "chr1_3514805_3515121", "chr1_3670855_3672134", 
"chr1_3936145_3936398"), Length = c(357L, 209L, 248L, 317L, 1280L, 
254L), gc_cont = c(0.384831, 0.418269, 0.48583, 0.5, 0.719312, 
0.359684)), .Names = c("Peakid", "Length", "gc_cont"), row.names = c(NA, 
6L), class = "data.frame")


df
#>                 Peakid Length  gc_cont
#> 1 chr1_3119849_3120205    357 0.384831
#> 2 chr1_3164889_3165097    209 0.418269
#> 3 chr1_3360993_3361240    248 0.485830
#> 4 chr1_3514805_3515121    317 0.500000
#> 5 chr1_3670855_3672134   1280 0.719312
#> 6 chr1_3936145_3936398    254 0.359684

我尝试做的是将Peakid变成行名。我尝试了但失败了:

> df %>%  column_to_rownames(var = "Peakid")
Error: `df` already has row names

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

我们将行名称设置为NULL,然后使用columns_to_rownames

df %>%
  `row.names<-`(., NULL) %>% 
   column_to_rownames(var = "Peakid")
#                     Length  gc_cont
#chr1_3119849_3120205    357 0.384831
#chr1_3164889_3165097    209 0.418269
#chr1_3360993_3361240    248 0.485830
#chr1_3514805_3515121    317 0.500000
#chr1_3670855_3672134   1280 0.719312
#chr1_3936145_3936398    254 0.359684