简体   繁体   English

有什么方法可以检测特定单词并将整个字符串替换为 R 语言中的另一个单词?

[英]Is there any way to detect a specific word and replace a whole string with another in R language?

I want to replace char value in R with another, it should be like this:我想把R中的char值换成另一个,应该是这样的

The key word to work is "Texas".工作的关键词是“德州”。 And there is any way that I can do it with multiple files at once.我可以通过任何方式一次处理多个文件。

I have tried like this: df[df=="121 Texas"]<-"Texas" but it's clearly not smart at all when it comes to work with many dataframe at the same time.我试过这样: df[df=="121 Texas"]<-"Texas"但在同时处理许多 dataframe 时显然一点也不聪明。

Let's say you had a dataframe with a column named "Original" and you wanted to replae all the entries in that column that contained the letters "Texas" as a substring with just the character value "Texas":假设您有一个 dataframe,其中包含一个名为“Original”的列,您想要将该列中包含字母“Texas”的所有条目替换为仅包含字符值“Texas”的 substring:

  df$Original[ grepl("Texas", df$Original) ] <- "Texas"

The grepl is one of the regex functions. grepl是正则表达式函数之一。 It returns a logical value.它返回一个逻辑值。 The "[" function on the LHS of "<-" (technically the "[<-" function) can accept a logical index and only do the replacements for those items that register TRUE in the grepl test. “<-”(技术上是“[<-”函数)的 LHS 上的“[”function 可以接受逻辑索引,并且只对那些在grepl测试中注册为 TRUE 的项目进行替换。

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

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