replace word in character sentence in R

Viewed 205

Ok so, how do I change a word in a character vector of length 1? To be more specific, I have the sentence "I want this book" in a character vector of length 1 apparently, and I want to replace the word "this" with "that" and then find how many words "that" exist in the sentence (which ofc will be 1). Questions; How do I do this? Do I have to change something in the vector to use another code? Like make each word a unique character? I want to do this with the simplest possible way, avoiding perplexed coding if it shall be possible... Thank you all!

2 Answers

To count you can use:

stringr::str_count("I want this book", "this")

And to replace:

stringr::str_replace("I want this book", "this", "that")

or in base R

gsub("this", "that", "I want this book", fixed = TRUE)

The below does what you requested.

myword <- "this is just that whatever mate this is it"
# 1. replace this with that
result <- gsub("this", "that", myword)
#2. count the "that" occurrences
length(unlist(strsplit(result, "that")))-1

or with stringr

library(stringr)
str_count(result, "that")
> str_count(result, "that")
[1] 3
> result
[1] "that is just that whatever mate that is it"
Related