### #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 ______________________________________________ R-help@r-project.org 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.