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

Extract column names character

I have a dataset dtAU where the columns names are the following:

...
"SUPG..SU.Product.Group"  
"SUPC..SU.Industry.Code" 
"SU_CAT..SU.Category"               
"FREQUENCY..Frequency" 
"TIME_PERIOD..Time.Period" 
...

I want to get the colnames as "SUPG", "SUPC", etc… so to extract only the character before the ".." and assign them as column names.

When I try this

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

test <- str_split(colnames(dtAU), "[..]")

I got :

List of 11
 $ : chr [1:3] "ï" "" "DATAFLOW"
 $ : chr [1:5] "SUPG" "" "SU" "Product" ...
 $ : chr [1:5] "SUPC" "" "SU" "Industry" ...
 $ : chr [1:4] "SU_CAT" "" "SU" "Category"
 $ : chr [1:3] "FREQUENCY" "" "Frequency"
 $ : chr [1:4] "TIME_PERIOD" "" "Time" "Period"
 $ : chr "OBS_VALUE"
 $ : chr [1:4] "UNIT_MEASURE" "" "Observation" "Comment"
 $ : chr [1:5] "UNIT_MULT" "" "Unit" "of" ...
 $ : chr [1:4] "OBS_STATUS" "" "Observation" "Comment"
 $ : chr [1:4] "OBS_COMMENT" "" "Observation" "Comment"

But I do not know how to retrieve as column names the first part of each character chain

>Solution :

You can do:

gsub('[..].*', '', names(dtAU)) -> names(dtAU)
gsub('\\..*', '', names(dtAU)) -> names(dtAU)

or if you want to use strsplit:

sapply(strsplit(names(dtAU), split = '\\.'), `[[`, 1) -> names(dtAU)
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