简体   繁体   English

在R中替换字符句子中的单词

[英]replace word in character sentence in R

Ok so, how do I change a word in a character vector of length 1?好的,如何更改长度为 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).更具体地说,我显然在长度为 1 的字符向量中有句子“我想要这本书”,我想用“那个”替换“这个”这个词,然后找出“那个”存在多少个词句子(哪个 ofc 将是 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!我想用最简单的方法来做到这一点,如果可能的话,避免困惑的编码......谢谢大家!

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或在基础 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或与stringr

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM