Is a feature has a match for a regex, I would like to use the value of the match to populate a new feature, else NA.
I found this post and tried to use the answer for my problem.
library(dplyr)
library(stringr)
dat.p <- dat.p %>%
mutate(
cad = ifelse(str_locate(text_field, "\\[[^]]*\\]"),
str_extract(text_field, "\\[[^]]*\\]"),
NA)
)
Where if there's a match for regex \\[[^]]*\\]
within text_field use that value in new column cad, else make the value of cad NA.
When I run it I get error:
Error: wrong result size (1000000), expected 500000 or 1
How do I do this?
Some example data:
df <- data.frame(
id = 1:2,
sometext = c("[cad] apples", "bannanas")
)
df.desired <- data.frame(
id = 1:2,
sometext = c("[cad] apples", "bannanas"),
cad = c("[cad]", NA)
)