Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pivot_longer with 2 groups of columns

Tags:

r

dplyr

tidyverse

This is my code

first_df<-tibble(y_1 = seq(0,1*3.14, length.out = 1000),
            y_2 = seq(0,2*3.14, length.out = 1000),
            y_3 = seq(0,3*3.14, length.out = 1000),
            y_4 = seq(0,.2*3.14, length.out = 1000),
            y_5 = seq(0,1*3.14, length.out = 1000),
            flower_1 = sin(y_1)-2.5,
            flower_2 = cos(y_2),
            flower_3 = sin(y_3)+2.5,
            flower_4 = cos(y_4)+5,
            flower_5 = sin(y_5)+7)

I want to do a pivot_longer with my output being 4 columns: x, y, values_flowers and values_y

The output should be something like this:

  flowers    y     value...2 value...4
   <chr>    <chr>     <dbl>     <dbl>
 1 flower_1 y_1       -2.5    0      
 2 flower_1 y_1       -2.50   0.00314
 3 flower_1 y_1       -2.49   0.00629
 4 flower_1 y_1       -2.49   0.00943
... ...     ...        ...     ... 
like image 670
Laura Avatar asked Dec 17 '22 11:12

Laura


1 Answers

Another solution:

library(tidyverse)

first_df %>% 
  pivot_longer(everything(),
               names_to = c(".value","flowers"),
               names_pattern = "([a-z]+_)(\\d)") %>%
  transmute(y=paste0("y_",flowers), flowers = paste0("flower_",flowers),
            value_flower=flower_, value_y=y_) %>% 
  arrange(y,flowers)
#> # A tibble: 5,000 × 4
#>    y     flowers  value_flower value_y
#>    <chr> <chr>           <dbl>   <dbl>
#>  1 y_1   flower_1        -2.5  0      
#>  2 y_1   flower_1        -2.50 0.00314
#>  3 y_1   flower_1        -2.49 0.00629
#>  4 y_1   flower_1        -2.49 0.00943
#>  5 y_1   flower_1        -2.49 0.0126 
#>  6 y_1   flower_1        -2.48 0.0157 
#>  7 y_1   flower_1        -2.48 0.0189 
#>  8 y_1   flower_1        -2.48 0.0220 
#>  9 y_1   flower_1        -2.47 0.0251 
#> 10 y_1   flower_1        -2.47 0.0283 
#> # … with 4,990 more rows
like image 110
PaulS Avatar answered Jan 15 '23 10:01

PaulS