What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table?

后端 未结 3 1820
南方客
南方客 2021-02-04 01:24

What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table? I have coded up a way to do this below. As I am

相关标签:
3条回答
  • 2021-02-04 02:04

    I had a similar problem to this -- I had a variable of factors in a long format and I wanted each factor to be a new column heading; using "unstack" from the stats library did it in one step. If the column you want as a header isn't a factor, "cast" from the reshape library might work.

    0 讨论(0)
  • 2021-02-04 02:13

    Well you could do it in 2 steps by using

    # Transpose table YOU WANT
    fooData.T <- t(fooData[,2:ncol(fooData)])
    
    # Set the column headings from the first column in the original table
    colnames(fooData.T) <- fooData[,1] 
    

    The result being a matrix which you're probably aware of, that's due to class issues when transposing. I don't think there will be a single line way to do this given the lack of naming abilities in the transpose step.

    0 讨论(0)
  • 2021-02-04 02:16

    Here are my two cents using dplyr for a data.frame that has grouping columns and an id column.

    id_transpose <- function(df, id){
      df %>% 
        ungroup() %>% 
        select(where(is.numeric)) %>% 
        t() %>% 
        as_tibble() %>% 
        setNames(., df %>% pull({{id}}))
    }
    
    0 讨论(0)
提交回复
热议问题