arrange()1. Rearrange the variable names in a data dictionary to match the order of the variables in the corresponding dataset
Review the data (df)
# A tibble: 3 x 7
p_id score1 score2 score3 demo1 demo2 demo3
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 123 20 25 32 1 1 0
2 225 15 23 18 0 1 0
3 194 22 24 29 0 1 1
Review the data dictionary
# A tibble: 7 x 2
var_name label
<chr> <chr>
1 p_id Study ID
2 score1 Score scale 1
3 demo1 Demographic item 1
4 score2 Score scale 2
5 demo2 Demographic item 2
6 score3 Score scale 3
7 demo3 Demographic item 3
First, pull the variable name order from the existing dataset.
Next, reorder var_name according to
df_names using dplyr::arrange() and
base::match().
dd %>%
dplyr::arrange(base::match(var_name, df_names))
# A tibble: 7 x 2
var_name label
<chr> <chr>
1 p_id Study ID
2 score1 Score scale 1
3 score2 Score scale 2
4 score3 Score scale 3
5 demo1 Demographic item 1
6 demo2 Demographic item 2
7 demo3 Demographic item 3
Another option is to use base::factor() and assign
levels.
dd %>%
dplyr::arrange(base::factor(var_name,levels = df_names))
Return to Reorder