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( data_original , direction = "wide" , idvar = "year" , timevar = "size" ) ans <- ans[ order( ans$year ), ] ans On October 21, 2022 2:03:19 PM PDT, Kelly Thompson <[email protected]> wrote: >### >#I have data presented in a "vertical" data frame as shown below in >data_original. >#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) ) ) > >data_original >data_expanded >mat > >______________________________________________ >[email protected] mailing list -- To UNSUBSCRIBE and more, see >https://stat.ethz.ch/mailman/listinfo/r-help >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. ______________________________________________ [email protected] mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.

