Search code examples
rdataframetranspose

Transpose DataFrame of 2 columns in R, in which 1 column has all the observations


my data frame has in the first column repeated labels, and in the second column all the observations. Its like a data frame made of multiple stacked data frames

Something like this:

Labels Observations
A x1a
B x1b
C x1c
A x2a
B x2b
C x2c
A x3a
B x3b
C x3c

I need something like this

A B C
x1a x1b x1c
x2a x2b x2c
x3a x3b x3c

Solution

  • You can do this using tidy::pivot_wider after creating a unique identifier for each Label:

    library(tidyr)
    library(dplyr)
    
    df %>%
      mutate(unique = row_number(), .by = Labels) %>%
      pivot_wider(names_from = Labels, values_from = Observations) %>% select(-unique)
    
    #   A     B     C    
    #   <chr> <chr> <chr>
    # 1 x1a   x1b   x1c  
    # 2 x2a   x2b   x2c  
    # 3 x3a   x3b   x3c