Replace String Based on the number of characters in r

Viewed 33

I have a data frame with two columns, one column consists of paragraphs(text) the other is the number of characters in the column with paragraphs. I would like to replace the paragraphs with less than 100 characters with "Read More..." while the ones with more than 100 characters remain the same.

paragraph Number of Characters
Paragraph 1 40
Paragraph 2 120

The result should be like:

paragraph Number of Characters
Read More.. 40
Paragraph 2 120
2 Answers
# Your data
df <- data.frame(paragraph = c("Paragraph 1", "Paragraph 2"),
           n_characters = c(40, 120))

df
#>     paragraph n_characters
#> 1 Paragraph 1           40
#> 2 Paragraph 2          120

# Replace values
df[df$n_characters < 100, "paragraph"] <- "Read More..."

df
#>      paragraph n_characters
#> 1 Read More...           40
#> 2  Paragraph 2          120

Another solution is to use case_when function from the dplyr package.

 df <- data.frame(paragraph = c("Paragraph 1", "Paragraph 2"),
                     `Number of Characters` = c(40, 120))
    library(dplyr)
    df %>% mutate(paragraph = 
      case_when(`Number.of.Characters` <100 ~ "Read More...",
                T ~ paragraph))
    
         paragraph Number.of.Characters
    1 Read More...                   40
    2  Paragraph 2                  120
Related