[R] getting data from a "vertical" table into a "2-dimensional" grid

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Sat Oct 22 00:03:07 CEST 2022

This operation goes by a variety of names... reshape (stats), cast (reshape2), spread (tidyr), and pivot_wider (tidyr).

The stats package reshape function is built-in, but uses terminology that can be confusing, and may not come out sorted the way you want so pre-converting to factor or post-sorting may be needed. Other packages may be easier to work with.

ans <- reshape(
, direction = "wide"
, idvar = "year"
, timevar = "size"
ans <- ans[ order( ans$year ), ]

On October 21, 2022 2:03:19 PM PDT, Kelly Thompson <kt1572757 using gmail.com> wrote:
>#I have data presented in a "vertical" data frame as shown below in
>#I want this data in a matrix or "grid", as shown below.
>#What I show below seems like one way this can be done.
>#My question: Are there easier or better ways to do this, especially
>in Base R, and also in R packages?
>#reproducible example
>data_original <- data.frame(year = c('1990', '1999', '1990', '1989'),
>size = c('s', 'l', 'xl', 'xs'),  n = c(99, 33, 3, 4) )
>data_expanded <- expand.grid(unique(data_original$year),
>unique(data_original$size), stringsAsFactors = FALSE )
>colnames(data_expanded) <- c('year', 'size')
>data_expanded <- merge(data_expanded, data_original, all = TRUE)
>mat <- matrix(data = data_expanded $n, nrow =
>length(unique(data_expanded $year)), ncol =
>length(unique(data_expanded $size)) , byrow = TRUE, dimnames = list(
>unique(data_expanded$year), unique(data_expanded$size) ) )
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

Sent from my phone. Please excuse my brevity.

More information about the R-help mailing list