convert_2wide | R Documentation |
convert_2wide
will convert a dataframe with multiple observations per group into one row with multiple columns.
convert_2wide(
data,
group_key,
value,
order_num = F,
fix_dates = T,
date_identifier = "DATE"
)
data |
A data object. |
group_key |
Name of grouping column, typicaly a unique ID. |
value |
Name of columns to be passed to |
order_num |
Character vector to define which type of table object was used (huxtable, xtable, or tables). |
fix_dates |
Logical vector, if |
date_identifier |
Character vector to identify date columns. |
The primary use case for this functions is to combine an individual with multiple time points (e.g. visits to clinic) into a single row with one column per
time point of interest. It is recommended to arrange (arrange
) columns of interest first, this ensures the first instance is actually the date before the next in sequence.
Re-ordering the columns may not work as expected unless the function is adjusted so that numeric value comes first, if that is the case, the columns could be arranged
by select(.,rcpt_uli, contains("1"), contains("2"), everything())
.
A converted data object in wide format.
gather
is a superseded function from tidyr
and may eventually be completely replaced by alternatives like pivot_wider
.
Adapted from Akrun's StackOverflow post: https://stackoverflow.com/questions/43695424/tidyr-spread-multiple-columns
To improve the function by doing spread operations separately and then joining back together, the following reference can be used:
https://stats.idre.ucla.edu/sas/modules/how-to-reshape-data-long-to-wide-using-proc-transpose/. Refer to pivot_wider
for a similar approach.
## Not run:
date_data <- data.frame(ID = c(123, 124, 125), AdmitDate = as.Date(c("2014-04-05", NA, "2016-02-03")), DOB = as.Date(c("1990-01-01", NA, NA)))
date_data <- dplyr::arrange(date_data, AdmitDate, DOB)
WideFormat <- convert_2wide(date_data, ID, value = AdmitDate:DOB)
# Alternative method is using tidyr::pivot_wider after naming groups
date_data <- data.frame(ID = c(123, 124, 125), AdmitDate = as.Date(c("2014-04-05", NA, "2016-02-03")), DOB = as.Date(c("1990-01-01", NA, NA)))
WideFormat <- dplyr::arrange(date_data, AdmitDate, DOB) %>%
dplyr::group_by(ID) %>%
dplyr::mutate(track = dplyr::row_number()) %>% dplyr::ungroup %>%
tidyr::pivot_wider(names_from = track, values_from = c(AdmitDate, DOB)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.