Online training class for Clinical R programming batch starts on Monday, 02Feb2026.
Click here for details.
wide<-tribble(
~usubjid,~HGB,~ALT,~AST,
"1001",13,30,23,
"1002",12,28,15,
)
long<-pivot_longer(wide,
cols=c(HGB,ALT,AST),
names_to = "lbtestcd",
values_to = "lbstresn"
) wide <- data.frame(
usubjid = c(1001, 1002),
HGB = c(13, 12),
ALT = c(30, 28),
AST = c(23, 15)
, stringsAsFactors = FALSE
)
long <- reshape(
wide,
varying = c("HGB", "ALT", "AST"),
v.names = "lbstresn",
timevar = "lbtestcd",
times = c("HGB", "ALT", "AST"),
idvar = "usubjid",
direction = "long"
)
row.names(long) <- NULL This code converts a dataset from wide format back to long format, which is the reverse of what pivot_wider() does in tidyverse.
The reshape() function is a base-R tool that handles both wide→long and long→wide transformations, depending on the direction argument.
The varying argument lists the columns that currently hold repeated measurements.
Here, HGB, ALT, and AST are the wide-format columns that will be stacked into rows.
The v.names argument defines the name of the value column in the long dataset.
All numeric results from the wide columns will be stored under lbstresn.
The timevar argument specifies the column that will identify which measurement each value belongs to.
In this case, lbtestcd will contain values like HGB, ALT, and AST.
The times argument supplies the actual labels that populate the timevar.
These correspond directly to the column names listed in varying.
The idvar argument defines the subject-level identifier that remains constant across reshaped rows.
Here, each usubjid will appear once per laboratory test.
Setting direction = "long" explicitly tells R we are reshaping from wide to long.
After reshaping, row names are automatically generated based on the original structure.row.names(long) <- NULL is used to reset them, giving a clean, sequential row order.