Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert dataframe from horizontal to vertical

I have data frame with values in this shape:

 col     x1   y1    x2   y2   x3  y3

 red     23  0.5    25  0.7   30  0.8

 blue    12  08     45  0.1   31  0.5

I need to convert this into two columns x and y:

col     x     y

I tried ‘pivot_longer’ but I can’t get the rigt pattern_sep or names_pattern

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  df1<- pivot_longer(df,
                  col = !col,
                  names_sep = "(.)(.)"
          )   

>Solution :

You can use reshape in base R

reshape(
    df,
    direction = "long",
    idvar = "col",
    varying = -1,
    v.names = c("x", "y")
)

which gives

        col time  x   y
red.1   red    1 23 0.5
blue.1 blue    1 12 8.0
red.2   red    2 25 0.7
blue.2 blue    2 45 0.1
red.3   red    3 30 0.8
blue.3 blue    3 31 0.5

Or pivot_*

df %>%
    pivot_longer(
        cols = !col,
        names_pattern = "(.)(.)",
        names_to = c("name", "id")
    ) %>%
    pivot_wider(id_cols = c(col, id))

or much shorter (thanks for comments from @Ritchie Sacramento)

df %>%
    pivot_longer(-col, names_pattern = "(\\D+)(\\d+)", names_to = c(".value", "id"))

which gives

# A tibble: 6 × 4
  col   id        x     y
  <chr> <chr> <dbl> <dbl>
1 red   1        23   0.5
2 red   2        25   0.7
3 red   3        30   0.8
4 blue  1        12   8
5 blue  2        45   0.1
6 blue  3        31   0.5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading