Search code examples
rdataframerow

Transpose rows and columns in data frame using first column entries as colnames in new R data frame


My data frame df looks like this:

      ID     A   B   C    D...Z
1   name1    4   6   7    8...
2   name2    5   8   3    5...
...
50 name50    4   6   7    8...

This is what I need:

   ID   name1   name2 ...name50 
1  A      4      5    ...  4
2  B      6      8    ...  6
etc.

I have tried the transpose command, as.data.frame(t(df)), but the index number for the rows (1,2,...50) becomes the column names, which I do not want. I would like to use the first column in the old data frame (name1, name2, ...) to become the column names of the new data frame. I also lose the index numbers for the rows, which I need.

Main problem is that df has about 15k rows, and 45 columns, so swapping rows and columns using brute force, is not that simple.

Yes, I need the data in a data frame.


Solution

  • library(tibble)
    library(dplyr)
    
    df %>%
      t() %>%
      as.data.frame(stringsAsFactors = F) %>%
      rownames_to_column("value") %>%
      `colnames<-`(.[1,]) %>%
      .[-1,] %>%
      `rownames<-`(NULL)
    

    Output is:

      ID name1 name2 name50
    1  A     4     5      4
    2  B     6     8      6
    3  C     7     3      7
    4  D     8     5      8
    

    Sample data:

    df <- structure(list(ID = c("name1", "name2", "name50"), A = c(4L, 
    5L, 4L), B = c(6L, 8L, 6L), C = c(7L, 3L, 7L), D = c(8L, 5L, 
    8L)), .Names = c("ID", "A", "B", "C", "D"), class = "data.frame", row.names = c(NA, 
    -3L))