Search code examples
rerror-handlingmultiple-columnssamplenames

shift col names by right without compromising the values


I have a data that looks like: enter image description here

I want to shift the ENSG0000000223972.5 to right by one without compromising the values. So that ENSG0000223972.5 should take place of ENSGOOOO227232.5 and so on. shift the col names by 1 position to right without changing the values. So eventually row1col1 name would be empty. I tried to do this:

names(genecount) = names(genecount)[-1]
                   

Solution

  • One possibility with base R is to first create an empty column (i.e., new), so that we can shift the column names to the right. Then, you want to use the names from the first column to the last column (minus the new column) to overwrite the column names. However, I also added in a name for the first column called name.

    df$new <- ""
    names(df)[1:ncol(df)] <- c("name", names(df)[1:ncol(df) - 1])
    

    Possible tidyverse solution:

    library(tidyverse)
    
    df %>%
      mutate(new = NA) %>%
      column_to_rownames(names(df)[1]) %>%
      rename_all(~names(df)) %>%
      rownames_to_column("name")
    

    Output

                          name ENSGO00000223972.5 ENSG00000227232.5 ENSGO0000278267.1 ENSGO0000243485.5
    1 GTEX-1117F-0226-SM-5GZZ7                  0               187                 0                  
    2 GTEX-1117F-0426-SM-5EGHI                  0               109                 0                  
    

    Data

    df <- structure(list(ENSGO00000223972.5 = c("GTEX-1117F-0226-SM-5GZZ7", "GTEX-1117F-0426-SM-5EGHI"),
                         ENSG00000227232.5 = c(0, 0),
                         ENSGO0000278267.1 = c(187, 109), ENSGO0000243485.5 = c(0, 0)),
                    class = "data.frame", row.names = c(NA, -2L))