I converted df
into a wide format (df_wide
), specifying that the names from the 'moderator_cat'
column in df
should come first when creating the new column names on the df_wide
data frame.
# create df
df <- data.frame(LIWC_name=c('rc_WC', 'rc_WC', 'rc_WC', 'rc_WC'),
OCEAN = c('O', 'O', 'E', 'E'),
moderator_cat = c('version', 'sample', 'version', 'sample'),
group1 = c(-.02, -.12, .34, .04),
group2 = c(-.13, .001, .12, .08),
group3 = c(NA, -.09, NA, .33))
# create wide version of df
df_wide <- pivot_wider(
data = df,
names_from = moderator_cat,
names_sep = "_",
values_from = c("group1":"group3"),
names_glue = "{moderator_cat}_{.value}"
)
So far everything works, but I'd like the columns in df_wide
to first go over all 'groups' (i.e., 'version_group1', 'version_group2', 'version_group3') and then do the same with the 'sample' variable (i.e., 'sample_group1', 'sample_group2', 'sample_group3'), instead of the order they have now (version_group1, sample_group1, version_group2, sample_group2, etc.). Is there a way to do this?