Home > database >  rename first column in R
rename first column in R

Time:04-19

I have this df and I would to rename the first colum with A, B, C

 DF <-
   seqnames    start      end width strand peak feature start_position end_position feature_strand insideFeature
A      chr1  3191703  3192103   401      *    1  X48094        3172239      3172348                   downstream
B      chr1  3482756  3483156   401      *    2  X48098        3445779      3448011              -      upstream
C      chr1  3549453  3549853   401      *    3  X48099        3535200      3537508              -      upstream

because when I save it as xls file the column names slip and no longer match. an example of output is:

    DF <-

COLNAMES   seqnames    start      end width strand peak feature start_position end_position feature_strand insideFeature
        A      chr1  3191703  3192103   401      *    1  X48094        3172239      3172348                   downstream
        B      chr1  3482756  3483156   401      *    2  X48098        3445779      3448011              -      upstream
        C      chr1  3549453  3549853   401      *    3  X48099        3535200      3537508              -      upstream

CodePudding user response:

You can use the rownames_to_column function from the tibble package. You can use the following code:

DF <- data.frame(row.names = LETTERS[1:2],
                 seqnames = c("chr1", "chr1"),
                 start = c(1, 3))

library(tibble)
DF %>%
  rownames_to_column(var="name")

Output:

  name seqnames start
1    A     chr1     1
2    B     chr1     3

CodePudding user response:

Assuming your column A, B, C represents row.names you could do this in base R:

DF <- data.frame(COLNAMES = LETTERS[1:3],
                 a = 1:3,
                 b = letters[1:3])

DF$row_nms <- COLNAMES(DF)

DF <- DF[, c("row_nms", "a", "b")]

DF
#>   COLNAMES a b
#> A       A 1 a
#> B       B 2 b
#> C       C 3 c

Or using {tibble}

library(tibble)

rownames_to_column(DF, var = "COLNAMES")
#>   COLNAMES row_nms a b
#> 1     A       A 1 a
#> 2     B       B 2 b
#> 3     C       C 3 c

Created on 2022-04-18 by the reprex package (v2.0.1)

  • Related