Search code examples
rdataframezipbind-rows

R zip dataframe rows


I have a dataframe in R with the following row-structure

rowA1
rowA2
rowA3
rowB1
rowB2
rowB3
rowC1
rowC2
rowC3

I want to reorder it that way:

rowA1
rowB1
rowC1
rowA2
rowB2
rowC2
rowA3
rowB3
rowC3

how?

edit: to clarify, the dataframe originally is composed out of 3 dataframes using bind_rows(A,B,C) each dataframe had 3 items.

Note that rowA1 etc. are exemplary and could contain any columns and values.


Solution

  • One dplyr option (instead of substr you can use readr::parse_number as Jon suggested):

    tibble::tribble(~row,
                    "rowA1",
                    "rowA2",
                    "rowA3",
                    "rowB1",
                    "rowB2",
                    "rowB3",
                    "rowC1",
                    "rowC2",
                    "rowC3") |> 
      dplyr::mutate(nbr = substr(row, 5,5)) |> 
      dplyr::arrange(nbr) |> 
      dplyr::select(-nbr)