convert_2wide: Convert a table to wide format

View source: R/convert.R

convert_2wideR Documentation

Convert a table to wide format

Description

convert_2wide will convert a dataframe with multiple observations per group into one row with multiple columns.

Usage

convert_2wide(
  data,
  group_key,
  value,
  order_num = F,
  fix_dates = T,
  date_identifier = "DATE"
)

Arguments

data

A data object.

group_key

Name of grouping column, typicaly a unique ID.

value

Name of columns to be passed to value in gather.

order_num

Character vector to define which type of table object was used (huxtable, xtable, or tables).

fix_dates

Logical vector, if TRUE date formats will be corrected.

date_identifier

Character vector to identify date columns.

Details

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()).

Value

A converted data object in wide format.

Note

gather is a superseded function from tidyr and may eventually be completely replaced by alternatives like pivot_wider.

Source

Adapted from Akrun's StackOverflow post: https://stackoverflow.com/questions/43695424/tidyr-spread-multiple-columns

See Also

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.

Examples

## 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)


al-obrien/farrago documentation built on April 14, 2023, 6:20 p.m.