In R, count words and enter a line break

Asked

Viewed 3,449 times

9

Dear friends, good afternoon

Suppose I have a vector the following way

caption<- c("I really liked the performance", "I didn’t like the performance", "I neither liked nor disliked")

I want to create a function that automatically enters the n separator every two words

For example

function(legend, 2)

"I liked the performance", "I liked the performance", "I neither liked it nor disliked it"

It would be interesting to generalize and determine the intervals of introduction of line break

for example, a function this way

function (vector, c(2,3,5))

where c(2,4,5) means that each vector element will be introduced a first n after two words, a second n after 3 words and a third n after 5 words.

2 answers

7


You can do it using regular Expression:

library(stringr)

legenda   <- c("Gostei muito da atuação" , "Gostei pouco da atuação", "Nem gostei e nem desgostei")

legenda2  <- str_replace_all(string      = legenda,
                             pattern     = "(\\w+\\s\\w+)",
                             replacement ="\\1 \n")
legenda2
[1] "Gostei muito \n da atuação \n"    "Gostei pouco \n da atuação \n"   
[3] "Nem gostei \n e nem \n desgostei"

To change the amount of words just put more \\w+\\s

0

You can do this using the function nbreak() that I created:

devtools::install_github("igorkf/breaker")
library(breaker)

legenda <- c("Gostei muito da atuação" , "Gostei pouco da atuação", "Nem gostei e nem desgostei")

purrr::map_chr(legenda, ~nbreak(.x, n = 2))
# [1] "Gostei muito\nda atuação"     "Gostei pouco\nda atuação"     "Nem gostei\ne nem\ndesgostei"

I haven’t implemented it for different vectors yet, as you mentioned (it’s a good idea)!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.