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 to extract a word from a column to their own separate column in r

For example I have a column where the characters go something like this

"Object=house colour=blue size=big", "Object=roof colour=red size=small", "Object=window colour=green size=medium"

I want to extract just the word after colour and create a new column. so it would look like this

"blue", "red", "green"

I have started trying to do this with str_extract but am very lost on how to specify things. So far I have

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

colour<- str_extract(string = df, pattern = "(?<=colour= ).*(?=\\,)")

How would I go about solving this?

>Solution :

There was no space after the = and also, we can use \\S+ to specify one or more non-white space

library(stringr)
str_extract(string = df, pattern = "(?<=colour=)\\S+")
[1] "blue"  "red"   "green"

data

df <- c("Object=house colour=blue size=big", "Object=roof colour=red size=small", 
"Object=window colour=green size=medium")
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