If data come from Nettskjema, the structure is in wide format, with each question option as columns, creating 21*4 columns of data. This function allows you to gather and create single columns for questions.
bdi_restructure(data, cols = matches("[0-9]_[0-9]"), sep = "_")
Data containing BDI data
Columns that contain BDI data
separator to use for the column names
data frame
The columns must adhere to some specific logic to work. It is recommended that the column names are in the format bdi_01_0 bdi_01_1 bdi_01_2 bdi_01_3, where the first two numbers are the question number, and the last number is the option number.
dat <- data.frame(
ID = 1:4,
bdi_01_0 = c(NA,1, NA, NA),
bdi_01_1 = c(1, NA, 1, NA),
bdi_01_2 = c(NA, NA, 1, NA),
bdi_01_3 = c(NA, NA, NA, NA),
bdi_02_0 = c(1, NA, NA, NA),
bdi_02_1 = c(NA,NA, NA, NA),
bdi_02_2 = c(NA,1, NA, NA),
bdi_02_3 = c(NA, NA, NA, 1)
)
bdi_restructure(dat)
#> # A tibble: 4 × 3
#> ID bdi_01 bdi_02
#> <int> <dbl> <dbl>
#> 1 1 1 0
#> 2 2 0 2
#> 3 3 1.5 NA
#> 4 4 NA 3