Wraps the function base::reshape() to mimic the behavior of the Stata reshape. Used to transform data.frames between "wide" and "long" formats.

wide_to_long(data, stub, i, j, clean = TRUE)

long_to_wide(data, stub, i, j, clean = TRUE)

Arguments

data

a data.frame

stub

a character string. For wide_to_long(), this is the leading character "stub" common to all varying columns to be collected into rows. For long_to_wide(), this is the name of the variable to be prefixed to the values of j and spread into columns.

i

a string. The name of the column in data that uniquely identifies each observation.

j

a string. For wide_to_long(), this will be the name for the new column that captures the values of the varying colums that follow the value passed to stub. For long_to_wide(), this is the name of an existing column, the values of which we be suffixed to stub as the observations are spread into 'wide' format.

clean

a logical value. If TRUE, the resulting data.frame is tidied automatically: attribute information from reshape() is removed, row names are reset to a numeric sequence, and column names are stripped of dots. Set to FALSE if you would like the immediate result from reshape().

Value

a data.frame.

Details

wide_to_long() and long_to_wide() are designed to closely mimic basic functionality of Stata's reshape command. See the examples below for intended usage.

References

http://www.stata.com/manuals13/dreshape.pdf

Examples

t <- "id,sex,inc80,inc81,inc82 1,0,5000,5500,6000 2,1,2000,2200,3300 3,0,3000,2000,1000" df1 <- read.csv(text = t) df2 <- wide_to_long(data = df1, stub = "inc", i = "id", j = "year") df3 <- long_to_wide(data = df2, stub = "inc", i = "id", j = "year") identical(df1, df3)
#> [1] TRUE
df4 <- long_to_wide(data = df2, stub = "inc", i = "id", j = "year", clean = FALSE) identical(df1, df4)
#> [1] FALSE