Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R reduce sentence to word

Tags:

string

regex

r

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"
like image 998
Wijb Dekker Avatar asked Oct 14 '25 20:10

Wijb Dekker


2 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" 
like image 92
Paul Avatar answered Oct 17 '25 10:10

Paul


Another option with sub

> sub("(.{1,24}(?<=\\S)(?= )).*", "\\1", fruits, perl = TRUE)
[1] "apples and oranges and" "pineapples and mangos"
like image 29
ThomasIsCoding Avatar answered Oct 17 '25 08:10

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!