gsub return an empty string when no match is found

后端 未结 7 1654
太阳男子
太阳男子 2021-01-12 04:35

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

7条回答
  •  粉色の甜心
    2021-01-12 05:18

    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+")) .

提交回复
热议问题