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
direction = "long"stacks the varying columns.timevarandidvarname the new key columns.- The same call with
"wide"reverses it.
Keywords and builtins used here
creshape
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.
Step 2 of 4 in Reshaping & combining, step 5 of 8 in Data frames in base R.