Search code examples
rtranspose

How do I transpose a dataframe properly in R


I am struggling with what I hope is a fairly basic problem in transposing a dataframe.

My dataframe has a structure like this:

Measure = c("Heightpercentile", "Weightpercentile", "Shoesize")
Value = c(56,60,10,45,48,7,78,60,9)
Person = c("ID4", "ID4", "ID4", "ID6", "ID6", "ID6", "ID7", "ID7", ID7")

So I have three columns and (in this example) nine rows, with three rows for each ID#.

And I would like a structure like this:

Person= c("ID4", "ID6", "ID7")
Heightpercentile = c(56,45,78)
Weightpercentile = c(60,47,60)
Shoesize = (10,7,9)

So four columns and three rows, with one row for each ID#.

I have been trying to work with transpose and was looking at pivot from dplyr but I'm just not getting it. Thanks!


Solution

  • You could use pivot_wider:

    library(tidyr)
    
    pivot_wider(df,names_from= "Person",values_from="Value") 
    
    
    # Measure            ID4   ID6   ID7
    #  <chr>            <dbl> <dbl> <dbl>
    #1 Heightpercentile    56    45    78
    #2 Weightpercentile    60    48    60
    #3 Shoesize            10     7     9
    
    

    or with data.table:

    library(data.table)
    
    setDT(df)
    
    dcast(df,Measure~Person,value.var = "Value")
    
    #Key: <Measure>
    #            Measure   ID4   ID6   ID7
    #             <char> <num> <num> <num>
    #1: Heightpercentile    56    45    78
    #2:         Shoesize    10     7     9
    #3: Weightpercentile    60    48    60
    

    data:

    df <- data.frame(Measure = c("Heightpercentile", "Weightpercentile", "Shoesize"),
                     Value = c(56,60,10,45,48,7,78,60,9),
                     Person = c("ID4", "ID4", "ID4", "ID6", "ID6", "ID6", "ID7", "ID7", "ID7"))