Paul
Paul

Reputation: 696

R Trim characters of items in Vector

I need to figure out how to trim the characters for every entry in a character vector. I have searched and tried to use a ^ when referring back to the vector but it has not worked. I am sure there is a simple way to do this that I am not aware of.

Example:

CV <- c("ABC_001", "ABC_002", "DEF_003", "DEF_004", "GHIJKLM_005", "GHIJKLM_006")

Desired format of character vector CV:

"ABC","ABC","DEF","DEF","GHIJKLM","GHIJKLM"

Thanks for your help!

Upvotes: 0

Views: 1319

Answers (2)

dmontaner
dmontaner

Reputation: 2165

In this particular example it seems that you want to more to split your strings using the underscore symbol. If that is the case you can use strsplit:

sapply (strsplit (CV, split = "_"), "[", 1)

Upvotes: 1

mac_staben
mac_staben

Reputation: 81

gsub("[^A-Z]", "", CV)

https://regex101.com/ I found this website very helpful for testing regular expressions. Good luck!

Upvotes: 2

Related Questions