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

How can I split up a string based on upper case and lower case in R?

I have a column with names where the surnames are all upper case and the first names are all in lower case except the first letter. How can I split this up?
Example: BIDEN Joe

names <- c("BIDEN Joe", "DE WEERDT Jan", "SCHEPERS Caro")

The result I want to achieve is to create to vectors/columns with in one the words with the capital letters so it becomes:

surnames <- c("BIDEN", "DE WEERDT", "SCHEPERS")

And in the other the first names:

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

first_names <- c("Joe", "Jan", "Caro")

Thank in advance

>Solution :

Try this:

names <- c("BIDEN Joe", "DE WEERDT Jan", "SCHEPERS Caro")

# Remove capitals followed by a space 
first_names  <- gsub("^[A-Z].+ ", "", names) 
#  "Joe"  "Jan"  "Caro"

# Replace a space followed by a capital followed by a lower case letter
last_names  <- gsub(" [A-Z][a-z].+$", "", names) 
# "BIDEN"     "DE WEERDT" "SCHEPERS"

Also I wouldn’t call the vector names as that is the name of a base function.

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