R reduce sentence to word

Viewed 34

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"

1 Answers

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" 
Related