typestar

Reshaping wide and long in R

Base R's reshape between wide and long layouts.

wide <- data.frame(
  id = 1:2,
  q1 = c(10, 20),
  q2 = c(15, 25)
)

long <- reshape(wide, direction = "long",
                varying = c("q1", "q2"),
                v.names = "value",
                timevar = "quarter",
                idvar = "id")

back <- reshape(long, direction = "wide",
                idvar = "id", timevar = "quarter")

How it works

  1. direction = "long" stacks the varying columns.
  2. timevar and idvar name the new key columns.
  3. The same call with "wide" reverses it.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
262
Tokens
86
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 54 seconds.

Type this snippet

Step 2 of 4 in Reshaping & combining, step 5 of 8 in Data frames in base R.

← Previous Next →