Home > Net >  Use `pivot_longer` to turn a 1x4 table into a 2x2 one
Use `pivot_longer` to turn a 1x4 table into a 2x2 one

Time:04-08

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())?

CodePudding user response:

You could do:

df <- data.frame(
  x_min=1,
  x_max=2,
  y_min=3,
  y_max=4)

tidyr::pivot_longer(df, everything(), names_to = c(".value", "name"), names_sep = "_")
#> # A tibble: 2 × 3
#>   name      x     y
#>   <chr> <dbl> <dbl>
#> 1 min       1     3
#> 2 max       2     4

CodePudding user response:

library(tidyverse)

df %>%
   pivot_longer(everything(), names_to = c('.value', 'rowname'), names_sep = '_')%>%
   column_to_rownames()
    x y
min 1 3
max 2 4
  • Related