Search code examples
rdataframereshapedata-manipulation

reshape R data frame long to wide


I'm trying to reshape my data from long to wide

set.seed(1)
y <- rnorm(12, 0, 1)
x <- rep(c("A","B"), each=6)
g <- rep(c("g1", "g2"), each=3)
t <-  rep(c(1,2,3), times=4)
df <- data.frame(y=y, x=x, g=g, t=t)

This is what I'm hoping to get:

    A.1     A.2     A.3    B.1     B.2     B.3
g1  -0.626  0.183  -0.835  0.487   0.738   0.575
g2  1.595   0.329  -0.820  -0.305  1.511   0.389

I tried with reshape

reshape(df, idvar = "g", timevar = "t", direction = "wide")

but I don't know how to add x to the columns


Solution

  • You can use pivot_wider. Also, I added a more compact form of your toy data set using expand.grid.

    library(tidyr)
    
    df <- data.frame(y=y, expand.grid(t=c(1,2,3), g=c("g1", "g2"), x=c("A","B")))
    pivot_wider(df, values_from = y, names_from = c(x,t), names_sep = ".")
    
      g        A.1   A.2    A.3    B.1   B.2   B.3
      <fct>  <dbl> <dbl>  <dbl>  <dbl> <dbl> <dbl>
    1 g1    -0.626 0.184 -0.836  0.487 0.738 0.576
    2 g2     1.60  0.330 -0.820 -0.305 1.51  0.390