Unstack one Set of Variables from Long to Wide
unstack2
converts one set of variables in a data.frame from long to wide format.
(If you want to convert multiple sets of variables from long to wide, see
reshape
.) It is a modified version of unstack
that 1) requires a
column for the rownames of the data.frame (or equivalently an id column with
unique values for each row in the wide format) before it was stacked, 2) can
retain additional columns not being unstacked, and 3) can order by rownames
original positions rather than their alphanumerical order.
unstack2( data, rownames.nm = "row_names", vrbnames.nm = "vrb_names", el.nm = "el", keep.nm = pick(x = names(data), val = c(rownames.nm, vrbnames.nm, el.nm), not = TRUE), rownamesAsColumn = FALSE )
data |
data.frame of data containing stacked variables. |
rownames.nm |
character vector of length 1 specifying the colname in
|
vrbnames.nm |
character vector of length 1 specifying the colname in
|
el.nm |
character vector of length 1 specifying the colname in |
keep.nm |
optional argument containing a character vector of colnames from
|
rownamesAsColumn |
logical vector of length 1 specifying whether the unique
values in |
unstack2
is also very similar to reshape::cast.data.frame
. The
differences are that it 1) can return the rownames as rownames of the returned
data.frame rather than an id column, 2) can retain additional columns not being
unstacked, and 3) can order by rownames original positions rather than the variable
names being stacked call order.
data.frame with nrow = length(unique(data[[rownames.nm]]))
from
unstacking the elements of el.nm
alongside one another. New columns are
created for each unique values in vrbnames.nm
as well as columns for any
colnames additional specified by keep.nm
. If rownamesAsColumn
= TRUE,
then the first column are the unique values in rownames.nm
; otherwise,
they are the rownames of the return object (default).
# 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.data.frame 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) # not able to keep additional variables y <- reshape::cast(data = stacked, formula = row_names ~ vrb_names, value = "el") # automatically sorts the rownames and does not include extra columns z <- unstack2(stacked) head(x); head(y); head(z)
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.