-1

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]
                   
Rhea Bedi
  • 123
  • 6
  • 1
    It's not hard to shift column names, but looking at the picture of output (_please_ use real data, pics are not good for several reasons) it looks as if it was read in incorrectly. Consider checking with your `read.*` function to see if adding `row.names=` helps. – r2evans Feb 21 '22 at 01:27
  • 1
    But your command cannot work, because the length on the LHS is different than the length on the RHS. – r2evans Feb 21 '22 at 01:28
  • 1
    Images: https://meta.stackoverflow.com/a/285557 (and https://xkcd.com/2116/). Reproducibility: (sample data, code, expected output) https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Feb 21 '22 at 01:28

1 Answers1

1

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))
AndrewGB
  • 16,126
  • 5
  • 18
  • 49