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 multiple rows into one column for a specific start of row name starting

From a dataframe like this:

df <- data.frame(row_name = c("sha1", "sha2", "edt1", "edt2", "perform1", "perform2"),
                 value = c(10, 20, 30, 40, 50, 60))

How is it possible to convert rows to columns to receive this result?

df <- data.frame(sha = c(10, 20), edt = c(30, 40), perform = c(50, 60))

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

>Solution :

You can do it first by separating the number from the words that you want to be the variable names. Then you can pivot_wider() on the names and then remove the variable that captured the number.

library(dplyr)
library(tidyr)
df <- data.frame(row_name = c("sha1", "sha2", "edt1", "edt2", "perform1", "perform2"),
                 value = c(10, 20, 30, 40, 50, 60))
df %>% 
  separate_wider_regex(row_name, c(name = "[^\\d]*", obs = "\\d")) %>%
  pivot_wider(names_from = "name", values_from = "value") %>% 
  select(-obs)
#> # A tibble: 2 × 3
#>     sha   edt perform
#>   <dbl> <dbl>   <dbl>
#> 1    10    30      50
#> 2    20    40      60

Created on 2023-06-23 with reprex v2.0.2

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