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

Separate a column with characters and numbers to two seperated columns for each class

I want to separate the 1st column of my dataframe named Demand Per Section to two separated columns named Units for characters and Demand for numeric values.

df<-structure(list(`Demand Per Section` = c("80 GM", "125ML", "350 ML", 
"100 GM", "538ML", "75GM", "25GM", "138GM", "138GM", "75GM"), 
    Formula = c("C10H8", "HNO3", "H2SO4", "C7H6O3", "CH3COOCOCH3", 
    "C10H8O", "NaOH", "C6H5NHNH2.HCl", "C6H12O6", "CH3COONa"), 
    `Element Name` = c("Naphthalene", "Nitric acid (concentrated)", 
    "Sulphuric acid(concentrated)", "2-hydroxybenzoic acid", 
    "Acetic anhydride", "2-Naphthol", "Sodium Hydroxide", "Phenyl hydrazine hydrochloride", 
    "Glucose", "Sodium acetate"), `Course Name` = c("Course 1", 
    "Course 1", "Course 1", "Course 1", "Course 1", "Course 1", 
    "Course 1", "Course 1", "Course 1", "Course 1"), Department = c("Chemsitry", 
    "Chemsitry", "Chemsitry", "Chemsitry", "Chemsitry", "Chemsitry", 
    "Chemsitry", "Chemsitry", "Chemsitry", "Chemsitry")), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

library(tidyverse)
df %>%
  mutate(Unit = str_extract(`Demand Per Section`, "[A-Z]?"), 
         Demand = str_extract(`Demand Per Section`, "[0-9]?")) %>%
  select(`Demand Per Section`,Unit,Demand)

>Solution :

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

As there are inconsistent spaces between the digits and letter, we may use a regex lookaround

library(dplyr)
library(tidyr)
df %>% 
  separate(`Demand Per Section`, into = c("Demand", "Unit"), 
     sep = "(?<=[0-9])(?=\\s?[A-Z])", remove = FALSE) %>% 
  mutate(Unit = trimws(Unit))
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