I have a 1-by-4 table that contains summary statistics of two variables. For example,
df <- data.frame(
x_min=1,
x_max=2,
y_min=3,
y_max=4)
df
x_min x_max y_min y_max
1 1 2 3 4
I'd like to shape it into a 2-by-2 format:
x y
min 1 3
max 2 4
I'm able to get the result by the following code:
df %>%
pivot_longer(everything(),names_to = 'stat',values_to = 'val') %>%
separate(stat,into = c('var','stat'),sep = '_') %>%
pivot_wider(names_from = var, values_from = val)
However, I feel that this is a bit too circuitous because it first converts df into a table that's way too "long", and then "widens" it back to the appropriate size.
Is there a way to use pivot_longer() to get directly to the final result (that is, without involving pivot_wider())?