๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R Reshaping Frames

reshape() changes a frame between wide and long layouts. A wide frame holds one column per attempt and a long frame holds one row per attempt.

Wide to long

The wide frame holds score1 and score2 as separate columns. reshape() stacks them into one score column and adds an attempt column.

wide <- data.frame(id = c(1, 2), score1 = c(8, 7), score2 = c(9, 10))
long <- reshape(wide, direction = "long", varying = c("score1", "score2"), v.names = "score", timevar = "attempt", idvar = "id")
print(long)

Long back to wide

The long frame goes back with direction set to wide. The result has score.1 and score.2 columns and keeps the dotted row names.

wide <- data.frame(id = c(1, 2), score1 = c(8, 7), score2 = c(9, 10))
long <- reshape(wide, direction = "long", varying = c("score1", "score2"), v.names = "score", timevar = "attempt", idvar = "id")
back <- reshape(long, direction = "wide", idvar = "id", timevar = "attempt")
print(back)

Reshape run times

The same call works on run times measured in seconds. varying names run1 and run2 and v.names names the stacked column seconds.

wide <- data.frame(id = c(1, 2), run1 = c(50, 62), run2 = c(48, 60))
long <- reshape(wide, direction = "long", varying = c("run1", "run2"), v.names = "seconds", timevar = "run", idvar = "id")
print(long)

Example

wide <- data.frame(id = c(1, 2), score1 = c(8, 7), score2 = c(9, 10))
long <- reshape(wide, direction = "long", varying = c("score1", "score2"), v.names = "score", timevar = "attempt", idvar = "id")
print(long)
back <- reshape(long, direction = "wide", idvar = "id", timevar = "attempt")
print(back)

Key points

  • The varying argument names the wide columns that hold the repeated values.
  • v.names names the single value column in the long frame.
  • timevar names the new column that records which attempt each row came from.
  • idvar names the column that identifies each person or item.
  • Long rows come out ordered by attempt first and then by id.
  • Reshaping back to wide gives one column per attempt, named score.1 and score.2.

In this example the wide frame first becomes a long frame with one row per attempt. The long frame then goes back to wide, and the printed result keeps the dotted row names from the long form.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

In the long frame from the first snippet, which row name comes first?