Simple reshaping a vector from long to wide or from wide to long shape by means of a single factor.

ToLong(x, varnames = NULL)
ToWide(x, g, by = NULL, varnames = NULL)

Arguments

x

the vector to be reshaped

g

the grouping vector to be used for the new columns. The resulting data.frame will return one column per grouplevel.

by

a vector to be used to merge the pieces of x. If this is left to NULL the pieces will be merged by rownames in the order they are supplied.

varnames

the variable names if not the grouping levels should be used.

Details

ToLong expects x as a matrix or a data.frame and reshapes it to a (long) factor representation. ToWide expects the vectors x, g, by, wheras x being the variable, g the splitting factor and by a vector for rowwise merging.

Value

the reshaped object

Author

Andri Signorell <andri@signorell.net>

See also

Examples

d.x <- read.table(header=TRUE, text="
AA BB CC DD EE FF GG
7.9 18.1 13.3 6.2 9.3 8.3 10.6
9.8 14.0 13.6 7.9 2.9 9.1 13.0
6.4 17.4 16.0 10.9 8.6 11.7 17.5
")

ToLong(d.x)
#>      grp    x
#> 1.AA  AA  7.9
#> 2.AA  AA  9.8
#> 3.AA  AA  6.4
#> 1.BB  BB 18.1
#> 2.BB  BB 14.0
#> 3.BB  BB 17.4
#> 1.CC  CC 13.3
#> 2.CC  CC 13.6
#> 3.CC  CC 16.0
#> 1.DD  DD  6.2
#> 2.DD  DD  7.9
#> 3.DD  DD 10.9
#> 1.EE  EE  9.3
#> 2.EE  EE  2.9
#> 3.EE  EE  8.6
#> 1.FF  FF  8.3
#> 2.FF  FF  9.1
#> 3.FF  FF 11.7
#> 1.GG  GG 10.6
#> 2.GG  GG 13.0
#> 3.GG  GG 17.5

# ToWide by row numbers (by = NULL)
ToWide(PlantGrowth$weight, PlantGrowth$group)
#>    ctrl trt1 trt2
#> 1  4.17 4.81 6.31
#> 2  5.33 4.32 5.26
#> 3  5.14 4.69 5.12
#> 4  5.58 4.17 5.54
#> 5  5.18 4.41 5.50
#> 6  6.11 3.59 5.37
#> 7  4.50 5.87 5.29
#> 8  4.61 3.83 4.92
#> 9  5.17 6.03 6.15
#> 10 4.53 4.89 5.80

# To wide aligned by key
set.seed(41)
PlantGrowth$nr <- c(sample(12, 10), sample(12, 10), sample(12, 10))
head(PlantGrowth)
#>   weight group nr
#> 1   4.17  ctrl  8
#> 2   5.58  ctrl  3
#> 3   5.18  ctrl  5
#> 4   6.11  ctrl 12
#> 5   4.50  ctrl  2
#> 6   4.61  ctrl 10

ToWide(PlantGrowth$weight, PlantGrowth$group, by=PlantGrowth$nr)
#>    by ctrl trt1 trt2
#> 1   1   NA 4.89 5.80
#> 2   2 4.50 4.17 5.12
#> 3   3 5.58   NA 5.26
#> 4   4   NA 6.03 6.31
#> 5   5 5.18 4.41   NA
#> 6   6 5.17 4.81 5.50
#> 7   7 5.33 4.69   NA
#> 8   8 4.17 5.87 5.29
#> 9   9 4.53 4.32 6.15
#> 10 10 4.61 3.83 4.92
#> 11 11 5.14   NA 5.37
#> 12 12 6.11 3.59 5.54