Home > Enterprise >  Replace String Based on the number of characters in r
Replace String Based on the number of characters in r

Time:07-22

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

CodePudding user response:

# 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
  •  Tags:  
  • r
  • Related