Pankaj Kaundal
Pankaj Kaundal

Reputation: 1022

Extract Values stored in a certain pattern from a string in R and store in a data frame

I have a string doc which is read as a single string / factor variable in R. Glimpse below:

this is a shirt here a="dhfaskdjfk" and this is the pair of jeans a="eruqiourmfmd". These are tees a="feriuwoeiru" and these are trousers a="eruawiorvnxmc"

I want a data frame out of it that has (value in a=""):

dhfaskdjfk
eruqiourmfmd
feriuwoeiru
eruawiorvnxmc

Upvotes: 1

Views: 29

Answers (1)

akrun
akrun

Reputation: 886928

We can use str_extract_all

library(stringr)
v1 <- str_extract_all(str1, '(?<=a=")[^"]+')[[1]]
v1 
#[1] "dhfaskdjfk"    "eruqiourmfmd"  "feriuwoeiru"   "eruawiorvnxmc"

d1 <- data.frame(v1, stringsAsFactors=FALSE)

data

str1 <- 'this is a shirt here a="dhfaskdjfk" and this is the pair of jeans a="eruqiourmfmd". These are tees a="feriuwoeiru" and these are trousers a="eruawiorvnxmc"'

Upvotes: 1

Related Questions