Wijb Dekker
Wijb Dekker

Reputation: 73

R reduce sentence to word

I am lookin for an efficient way to reduce a large sentence to a specific length and ending on an entire word.

For example reduce each sentence to max 24 characters and end on whole word.

fruits <- c(
  "apples and oranges and pears and bananas",
  "pineapples and mangos and guavas"
)

to

"apples and oranges and", "pineapples and mangos"

Upvotes: 4

Views: 66

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101335

Another option with sub

> sub("(.{1,24}(?<=\\S)(?= )).*", "\\1", fruits, perl = TRUE)
[1] "apples and oranges and" "pineapples and mangos"

Upvotes: 1

Paul
Paul

Reputation: 9087

Take an extra character, then remove everything after (and including) the last space.

fruits <- c(
  "apples and oranges and pears and bananas",
  "pineapples and mangos and guavas"
)

n <- 24

sub(
  " [^ ]*$",
  "",
  substr(fruits, 1, n + 1)
)
#> [1] "apples and oranges and" "pineapples and mangos" 

Upvotes: 3

Related Questions