简体   繁体   English

将数据框内容与字符匹配并用特定单词替换匹配项(在 R 中)

[英]Match data frame content with a character and replace the match with a specific word (in R)

I have a data frame with one column X. In addition, I have an object (ob) class (character).我有一个包含一列 X 的数据框。此外,我还有一个 object(ob)class(字符)。 I would like to create a new object (ob1) were characters in ob that match df content are replaced with the word "word".我想创建一个新的 object (ob1),将 ob 中匹配 df 内容的字符替换为单词“word”。

df
   X
1 ABC
2 ACC
3 ATT
ob

[1] "ABC", "ACC", "ATT", "AGG", "ACT"

result结果

ob1

[1] "word", "word", "word", "AGG", "ACT"

Combining ifelse with %in% should do the job:ifelse%in%结合起来应该可以完成这项工作:

ob <- c("ABC", "ACC", "ATT", "AGG", "ACT")
df <- data.frame(x = c("ABC", "ACC", "ATT"))

ifelse(ob %in% df$x, yes = "word", no = ob)

Here is an approach with stringi :这是stringi的一种方法:

library(stringi)
sapply(ob,function(x)stri_replace_all_fixed(x,df$X,"word",vectorize_all = FALSE))
   ABC    ACC    ATT    AGG    ACT 
"word" "word" "word"  "AGG"  "ACT" 

Data:数据:

df<-structure(list(X = c("ABC", "ACC", "ATT")), class = "data.frame", row.names = c("1", 
"2", "3"))
ob<-c("ABC", "ACC", "ATT", "AGG", "ACT")

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

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