1
votes

I cannot get my head around gsub(). If text is:

 text <- "Genus_species_1652_NL"

How would I extract to get

"Genus species"

Thanks. This is a useful link but I havnt been able to sort it http://biostat.mc.vanderbilt.edu/wiki/pub/Main/SvetlanaEdenRFiles/regExprTalk.pdf

1
Could you explain why you would use gsub() for this and not, e.g., strsplit()? What are the constraints you are working under? - Stephan Kolassa
And if you were to try strsplit, one option might be: unlist(lapply(strsplit(text, "_",), "[", 1:2)) - Ben
@NickCrouch, could you please accept one as an answer, so that the question doesn't remain open? Both the answers clearly give what you've asked for. - Arun

1 Answers

3
votes

You can do this like:

> gsub('([A-z]+)_([A-z]+)_.*', '\\1 \\2', text)
[1] "Genus species"

but as mentioned in a comment, a tool like strsplit may be more useful.