long2wide {quest} | R Documentation |
Reshape Multiple Scores From Long to Wide
Description
long2wide
reshapes data from long to wide. This if often necessary to
do with multilevel data where variables in the long format seek to be
reshaped to multiple sets of variables in the wide format. If only one column
needs to be reshaped, then you can use unstack2
or
cast
- but that does not work for *multiple* columns.
Usage
long2wide(
data,
vrb.nm,
grp.nm,
obs.nm,
sep = ".",
colnames.by.obs = TRUE,
keep.attr = FALSE
)
Arguments
data |
data.frame of data. |
vrb.nm |
character vector of colnames from |
grp.nm |
character vector of colnames from |
obs.nm |
character vector of length 1 with a colname from |
sep |
character vector of length 1 specifying the string that separates
the name prefix (e.g., score) from it's number suffix (e.g., timepoint). If
|
colnames.by.obs |
logical vector of length 1 specifying whether to sort
the return object colnames by the observation label (TRUE) or by the order
of |
keep.attr |
logical vector of length 1 specifying whether to keep the
"reshapeWide" attribute (from |
Details
long2wide
uses reshape(direction = "wide")
to reshape the data.
It attempts to streamline the task of reshaping long to wide as the
reshape
arguments can be confusing because the same arguments are used
for wide vs. long reshaping. See reshape
if you are
curious.
Value
data.frame with nrow equal to nrow(unique(data[grp.nm]))
and
number of reshaped columns equal to length(vrb.nm) *
unique(data[[obs.nm]])
. The colnames will have the structure
paste0(vrb.nm, sep, unique(data[[obs.nm]]))
. The reshaped colnames
are sorted by the observation labels if colnames.by.obs
= TRUE and
sorted by vrb.nm
if colnames.by.obs
= FALSE. Overall, the
columns are in the following order: 1) grp.nm
of the groups, 2)
reshaped columns, 3) additional columns that were not reshaped.
See Also
Examples
# SINGLE GROUPING VARIABLE
dat_long <- as.data.frame(ChickWeight) # b/c groupedData class does weird things...
w1 <- long2wide(data = dat_long, vrb.nm = "weight", grp.nm = "Chick",
obs.nm = "Time") # NAs inserted for missing observations in some groups
w2 <- long2wide(data = dat_long, vrb.nm = "weight", grp.nm = "Chick",
obs.nm = "Time", sep = "_")
head(w1); head(w2)
w3 <- long2wide(data = dat_long, vrb.nm = "weight", grp.nm = "Chick",
obs.nm = "Time", sep = "_T", keep.attr = TRUE)
attributes(w3)
# MULTIPLE GROUPING VARIABLE
tmp <- psychTools::sai
grps <- interaction(tmp[1:3], drop = TRUE)
dups <- duplicated(grps)
dat_long <- tmp[!(dups), ] # for some reason there are duplicate groups in the data
vrb_nm <- str2str::pick(names(dat_long), val = c("study","time","id"), not = TRUE)
w4 <- long2wide(data = dat_long, vrb.nm = vrb_nm, grp.nm = c("study","id"),
obs.nm = "time")
w5 <- long2wide(data = dat_long, vrb.nm = vrb_nm, grp.nm = c("study","id"),
obs.nm = "time", colnames.by.obs = FALSE) # colnames sorted by `vrb.nm` instead
head(w4); head(w5)