# ordered by rownames
stacked <- stack2(data = mtcars, select.nm = c("disp","hp","drat","wt","qsec"),
keep.nm = c("vs","am"), order.by.rownames = TRUE)
x <- unstack2(stacked)
# ordered by vrbnames
stacked <- stack2(data = mtcars, select.nm = c("disp","hp","drat","wt","qsec"),
keep.nm = c("vs","am"), order.by.rownames = FALSE)
y <- unstack2(stacked)
identical(x, y)
# rownames as a column
z <- unstack2(data = stacked, rownamesAsColumn = TRUE)
# compare to utils:::unstack.data.frame and reshape::cast
stacked <- stack2(data = mtcars, select.nm = c("disp","hp","drat","wt","qsec"),
keep.nm = c("vs","am"))
x <- unstack(x = stacked, form = el ~ vrb_names) # automatically sorts the colnames alphabetically
y <- reshape::cast(data = stacked, formula = row_names ~ vrb_names,
value = "el") # automatically sorts the rownames alphabetically
z <- unstack2(stacked) # is able to keep additional variables
head(x); head(y); head(z)
# unequal number of rows for each unique value in `data`[[`vrbnames.nm`]]
# this can occur if you are using unstack2 without having called stack2 right before
row_keep <- sample(1:nrow(stacked), size = nrow(stacked) / 2)
stacked_rm <- stacked[row_keep, ]
unstack2(data = stacked_rm, rownames.nm = "row_names", vrbnames.nm = "vrb_names", el.nm = "el")
if (FALSE) # error when `add.missing` = FALSE
unstack2(data = stacked_rm, rownames.nm = "row_names", vrbnames.nm = "vrb_names",
el.nm = "el", add.missing = FALSE)
Run the code above in your browser using DataLab