I have the following data frame:
library(tidyverse)
dat <- tribble(
~Scenario, ~V1, ~V2, ~V3, ~V4,
1, 0.97, 0.46, 0.79, 0.25,
1, 0.21, 0.45, 0.23, 0.63,
1, 0.95, 0.97, 0.07, 0.61,
1, 0.93, 0.79, 0.23, 0.86,
2, 0.22, 0.01, 0.42, 0.47,
2, 0.71, 0.17, 0.16, 0.88,
3, 0.73, 0.38, 0.10, 0.77,
3, 0.49, 0.37, 0.90, 0.52,
3, 0.99, 0.71, 0.66, 0.05,
3, 0.72, 0.75, 0.69, 0.01,
3, 0.15, 0.87, 0.12, 0.02,
4, 0.94, 0.30, 0.91, 0.99)
I'm adding four new columns to this data, where each new column represents the sum of each V1:V4 column grouped by Scenario
:
dat_new <- dat %>%
group_by(Scenario) %>%
mutate_at(vars(-group_cols()), .funs = list(sum = sum))
And now I want to pivot this data into long format, where one set are my V1:V4 columns and the second set are my V1_sum:V4_sum columns. The normal pivot_longer
doesn't work because it only accepts one value column, however, I need two.
I found a potential solution in the tidyverse reference (example at the very bottom), but I'm failing with defining the correct names_pattern
. https://tidyr.tidyverse.org/reference/pivot_longer.html
Is there a simple and straightforward way (ideally tidyverse) where I can just do these two pivot_longer sets? It feels that this is one of the basic tasks when reshaping data sets, but I'm unable to get it working.
Expected output:
Scenario set V sum
1 1 0.97 3.06
1 2 0.46 2.67
1 3 0.79 1.32
1 4 0.25 2.35
...
4 4 0.99 0.99
Note: the column names "set", "V", and "sum" are just examples, and I'm fine with other column names if they are easier to generate on the fly.