Reshape
Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.
reshape
Wide to long
Stata
reshape long var, i(id) j(year)R Package:tidyr
tidyr::pivot_longer(data, tidyselect::starts_with("var"), names_to = "year", names_prefix = "var", names_transform = list(year = as.integer), values_to = "var")Differs from Stata Converts numeric suffixes to integer year values, matching reshape long without string. pivot_longer() returns a text year without names_transform and does not enforce reshape i()/j() uniqueness constraints.
Long to wide
Stata
reshape wide var, i(id) j(year)R Package:tidyr
pivot_wider(data, names_from = year, values_from = var, names_prefix = "var")Differs from Stata Duplicate keys can create list-columns in pivot_wider(); Stata reshape wide rejects duplicate i()/j() combinations. Validate keys first.
2 more examples and alternatives
Reshape repeated measurements to long form with base R
Stata
reshape long var, i(id) j(year)R Package:stats
stats::reshape(data, direction = "long", varying = list(c("var2000", "var2001")), v.names = "var", timevar = "year", times = c(2000, 2001), idvar = "id")Differs from Stata Explicitly list the wide columns and time values. This fixed workflow uses var2000 and var2001; adapt those names to your data.
Reshape repeated measurements to wide form with base R
Stata
reshape wide var, i(id) j(year)R Package:stats
stats::reshape(data, direction = "wide", v.names = "var", timevar = "year", idvar = "id", sep = "")Differs from Stata Requires one row per id/year combination. R row ordering and attributes differ from Stata; compare keys and values explicitly.
xpose
Transpose the data
Stata
xpose, clearR Package:tibble
tibble::as_tibble(t(data), .name_repair = "unique")