I\'m using the gsub
function in R to return occurrences of my pattern (reference numbers) on a list of text. This works great unless no match is found, in whic
Try strapplyc
in the gsubfn package:
library(gsubfn)
L <- fn$sapply(unlist(data), ~ strapplyc(x, "Ref. \\d+"))
unlist(fn$sapply(L, ~ ifelse(length(x), x, "")))
which gives this:
a sentence with citation (Ref. 12) another sentence without reference
"Ref. 12" ""
If you don't mind list output then you could just use L and forget about the last line of code. Note that the fn$
prefix turns the formula arguments of the function its applied to into function calls so the first line of code could be written without fn
as sapply(unlist(data), function(x) strapplyc(x, "Ref x. \\d+"))
.