Long to wide format... how is it again?

spunky

Can't make spagetti
#1
Hi!

It's been years since the last time I've had to do this. I thought it was simple, but I haven't been able to figure this one out...

.... how do I switch from long to wide format in R?

Like, say I have this:

Code:
x <- rnorm(100)
g <- rep(1:10, each=10)
df <- data.frame(x,g)
How do I turn this so that there are 10 columns (g.1, g.2, g.3,...g.10) and 10 rows? I remember this was super easy to do with reshape... alas:

Code:
> reshape(data=df, timevar="g", direction="wide")
Error in `[.data.frame`(data, , idvar) : undefined columns selected
For some reason, every time I try something I can't seem to get it! I'm not married to reshape. I know the tidyverse can also do this. I'm just not as well-versed on it but at this point I'll try anything!
 

spunky

Can't make spagetti
#2
OH I AM SUCH A DUM DUM! @spunky can be a DUM DUM sometiiiiimes! It turns out I was missing an 'id' variable to identify who is being measured within each group g.

So something like

Code:
x <- rnorm(100)
g1 <- rep(1:5, each=20)
id <- rep(1:20, times=5) ##this was missing!
df <- data.frame(x,id,g1)

reshape(df, idvar = "id", timevar = "g1", direction = "wide")
 

gianmarco

TS Contributor
#4
OH I AM SUCH A DUM DUM! @spunky can be a DUM DUM sometiiiiimes! It turns out I was missing an 'id' variable to identify who is being measured within each group g.

So something like

Code:
x <- rnorm(100)
g1 <- rep(1:5, each=20)
id <- rep(1:20, times=5) ##this was missing!
df <- data.frame(x,id,g1)

reshape(df, idvar = "id", timevar = "g1", direction = "wide")
At least, you are like that sometimes....I am like that most of the time!!!!
 
#6
Just posting another solution @spunky

If you're working in the tidyverse, tidyr has some relatively recent developments to help with these tasks, namely through pivot_wider, pivot_longer:

Code:
# data
x <- rnorm(100)
g1 <- rep(1:5, each=20)
id <- rep(1:20, times=5)
df <- data.frame(x,id,g1)


# example long to wide
library(tidyverse)

df2 <- df %>%
  pivot_wider(id_cols = 'id',
              names_from = 'g1',
              values_from = 'x',
              names_prefix = "time_")

# example going back to wide from long
df3 <- df2 %>%
  pivot_longer(cols = starts_with("time_"))