# From data.frame to matrix
df = data.frame(party = c("A", "A", "A", "B", "B", "B"),
region = c("III", "II", "I", "I", "II", "III"),
seats = c(5L, 3L, 1L, 2L, 4L, 6L))
pivot_to_matrix(df)
# from matrix to data.frame
mtrx = matrix(1:6, nrow = 2)
pivot_to_df(mtrx)
# from matrix to data.frame using dimnames
dimnames(mtrx) <- list(party = c("A", "B"), region = c("I", "II", "III"))
pivot_to_df(mtrx, "seats")
# Note that pivot results are sorted
pivot_to_df(pivot_to_matrix(df)) == df[order(df[[1]], df[[2]]),]
Run the code above in your browser using DataLab