I have a data frame with something like:
borg_dx, borg_sx, borg_dominant, borg_nondominant
which contains the integer values of the borg scale for the right, left, dominant and non dominant side.
Then i have another set of columns called:
borg_category_dx, borg_category_sx, borg_category_dominant, borg_category_nondominant,
which has character values for the category of borg (no effort, some effort, ecc.)
df1 <- data.frame( borg_dx = c(0,1), borg_sx = c(3,1), borg_dominant = c(3,1), borg_nondominant = c(0,8), borg_category_dx = c("no effort", "no effort"), borg_category_sx = c("light effort", "no effort"), borg_category_dominant = c("light effort", "no effort"), borg_category_nondominant = c("no effort", "high effort"))
I want to pivot the data frame into a long format where one column is the side, one column is the borg value and one column is the borg category, like this:
df_long <- data.frame(side = c("dx", "sx", "dom", "nondom", "dx", "sx", "dom", "nondom"), borg_value = c(0,3,3,0,1,1,1,8), borg_category = c("no effort", "no effort", "light effort", "no effort", "light effort", "no effort", "no effort", "high effort"))
if i just wanted to pivot borg values or categories, i could just do:
pivot_longer(
cols = starts_with("borg"),
names_to = "side",
names_prefix = "borg_",
values_to = "borg_value")
but having to send all suffixes (dx, sx, dominant, nondominant) to one column called side, and the values to two columns, i found from other answers that i should use something like:
pivot_longer(
cols = starts_with("borg"),
names_to = c(".value", "side"),
names_prefix = "borg",
names_pattern = ??????
except i have no idea how to phrase the regex bit. i don't know if i should just rename the columns to use just one underscore and a different separator.
From your description it sounds like your data looks something like below.
dput()output for replication:As a tibble:
The
name_prefixargument ofpivot_longer()removes the prefix before thename_patternis applied. In this case the prefix is useful to tell the borg values and borg categories apart. Inname_patternwe use parenthesis to define two extraction groups; the first one “(.*)” captures everything up until the second underscore, leaving everything after the underscore for the second group.