Last active
November 23, 2015 12:31
-
-
Save mrdwab/cb8e7014f9c10e4b0c16 to your computer and use it in GitHub Desktop.
Extracts a certain number of words from a text string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| wordExtract <- function(instring, number, start = TRUE, after = NULL) { | |
| len <- length(gregexpr("\\S+", instring)[[1]]) | |
| mlen <- if (is.null(after)) number else number + after | |
| if (len <= mlen) stop("can't do what you've asked for....") | |
| if (!is.null(after) & !isTRUE(start)) { | |
| start <- TRUE | |
| message("start specified as FALSE but ignored") | |
| } | |
| if (!is.null(after)) { | |
| pat <- "^(?:\\S+\\s+){%d}((?:\\S+\\s+){%d}\\S+).*" | |
| pat <- sprintf(pat, after, number-1) | |
| } else { | |
| pat <- if (isTRUE(start)) "^((?:\\S+\\s+){%d}\\S+).*" | |
| else "^.*\\s+((?:\\S+\\s+){%d}\\S+)$" | |
| pat <- sprintf(pat, number-1) | |
| } | |
| sub(pat, "\\1", instring, perl = TRUE) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: