Chris McKelt
Chris McKelt

Reputation: 1388

R get N words from a sentence as a string

In R how can I write a function where given a sentence I can pass an integer argument that returns the end words as a character string

EG

sentence <- "The quick brown fox jumps over the lazy dog"
result <- get_words(sentence, 2)

result should equal "lazy dog"

The function should include guard clauses and return the last word if the total words requested exceeds the words in the sentence

Upvotes: 0

Views: 1297

Answers (3)

Barbara
Barbara

Reputation: 1168

You can do it with the stringr library.

library(stringr)

sentence <- "The quick brown fox jumps over the lazy dog"
word(sentence, start = -2, end = -1)

Edited after tyluRp's suggestion.

Upvotes: 1

hrbrmstr
hrbrmstr

Reputation: 78792

Pure stringi solution (stringr::word() is overkill and uses more stringi functions than this. stringr handicap-wraps stringi functions):

library(stringi)

sentence <- "The quick brown fox jumps over the lazy dog"

tail(stri_extract_all_words(sentence)[[1]], 2)
## [1] "lazy" "dog" 

stri_join(tail(stri_extract_all_words(sentence)[[1]], 2), collapse=" ")
## [1] "lazy dog"

Actually readable version:

library(magrittr)

stri_extract_all_words(sentence)[[1]] %>% 
  tail(2) %>% 
  stri_join(collapse=" ")
## [1] "lazy dog"

It also uses a better, locale-sensitive word-break algorithm which is superior to base R's.

Upvotes: 1

jogo
jogo

Reputation: 12559

sentence <- "The quick brown fox jumps over the lazy dog"
paste(tail(strsplit(sentence, "\\s+")[[1]], 2), collapse=" ")

Upvotes: 1

Related Questions