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

Kelly Thompson kt1572757 @end|ng |rom gm@||@com
Fri Oct 21 23:03:19 CEST 2022

#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) ) )


More information about the R-help mailing list