Levittstyle
Levittstyle

Reputation: 115

Reshape using columns as categories

Any R code to reshape this data frame from:

big small year
1 70.9 60.3 2000
2 70.7 40.4 2001
3 70.8 55.2 2002

to:

size values year
1 big 70.9 2000
2 small 60.3 2000
3 big 70.7 2001
4 small 40.4 2001
5 big 70.8 2002
6 small 55.2 2002

Is there a neat way to do it in base R (if not package solution is also ok)?

Any help appreciated thanks!

Upvotes: 1

Views: 188

Answers (3)

akrun
akrun

Reputation: 886938

As the OP mentioned base R solution, here is one with reshape

out <- reshape(df1, idvar = "year", direction = 'long',
    times = names(df1)[1:2], varying = list(1:2), timevar = "size", 
       v.names = "values")
row.names(out) <- NULL

-output

> out
  year  size values
1 2000   big   70.9
2 2001   big   70.7
3 2002   big   70.8
4 2000 small   60.3
5 2001 small   40.4
6 2002 small   55.2

data

df1 <- structure(list(big = c(70.9, 70.7, 70.8), small = c(60.3, 40.4, 
55.2), year = 2000:2002), class = "data.frame", row.names = c("1", 
"2", "3"))

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 101044

A base R option

> cbind(year = df$year, rev(stack(df[1:2])))[order(c(row(df[1:2]))),]
  year   ind values
1 2000   big   70.9
4 2000 small   60.3
2 2001   big   70.7
5 2001 small   40.4
3 2002   big   70.8
6 2002 small   55.2

A data.table option

> setorder(melt(setDT(df), id.vars = "year"), "year")[]
   year variable value
1: 2000      big  70.9
2: 2000    small  60.3
3: 2001      big  70.7
4: 2001    small  40.4
5: 2002      big  70.8
6: 2002    small  55.2

Upvotes: 1

GuedesBF
GuedesBF

Reputation: 9858

You are looking for the pivot_longer() function from the dplyrpackage

library(dplyr)

df %>% pivot_longer(cols=c('big', 'small'), names_to='size', values_to='values'))

Upvotes: 3

Related Questions