r - 将包含某个单词的字符串替换为该单词
问题描述
我的 df 中有一个包含许多不同字符串的列,例如,一个字符串会说在 a 点交叉,或者从 a 点进入。我想用一个替换整个字符串,我该怎么做呢?
解决方案
Following a comment to the question by user Allan Cameron, here is a full solution with the suggestion I made.
df1 <- data.frame(col = c("crossed at point a",
"doesn't match though it has as",
"came in through point a",
"no"))
df1$col[grepl("\\ba\\b", df1$col)] <- "a"
df1
# col
#1 a
#2 doesn't match though it has as
#3 a
#4 no
Edit
Following another comment by Allan Cameron I have decided to write a small function to make it easier to replace a string that contains a word by that word.
replaceWord <- function(x, word){
pattern <- paste0("\\b", word, "\\b")
i <- grep(pattern, x)
x[i] <- word
x
}
replaceWord(df1$col, "a")
推荐阅读
- java - 关于循环内异常(try-catch)的问题
- java - 如何在android studio的视频播放器中获取视频文件目录
- node.js - 如何代理(或定义中间件)以阻止/允许我的 React 组件中的某些方法调用?
- vue.js - 复杂对象的对象反应性
- flutter - Flutter:如何获取设备屏幕 DPI 值
- python-3.x - 为什么函数不被调用一次?(Python:Tkinter,Matplotlib)
- c - 如何修复 realloc():C 中的下一个大小无效
- ruby - 在ruby中右键单击context_click,我无法选择“保存图像”选项
- azure-devops - 我们可以使用变量替换来更改任何文件类型,而不仅仅是 JSON 或 XML
- angular - 带有动态清晰度选项卡的角度表单在添加选项卡后获得 ExpressionChangedAfterItHasBeenCheckedError