如何准确地grep一个词 [英] How to grep a word exactly

查看:37
本文介绍了如何准确地grep一个词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想 grep 为氮";在以下字符向量中并希望得到仅返回包含氮"的条目;其余的都没有(例如固氮):

I'd like to grep for "nitrogen" in the following character vector and want to get back only the entry which is containing "nitrogen" and nothing of the rest (e.g. nitrogen fixation):

varnames=c("nitrogen", "dissolved organic nitrogen", "nitrogen fixation", "total dissolved nitrogen", "total nitrogen")

我尝试过这样的事情:

grepl(pattern= "![[:space:]]nitrogen![[:space:]]", varnames)

但这不起作用.

推荐答案

要获得完全等于nitrogen"的索引,您可以使用

To get the indices that are exactly equal to "nitrogen" you could use

which(varnames == "nitrogen")

根据您想要做什么,您甚至可能不需要 'which',因为 varnames == "nitrogen" 给出了 TRUE/FALSE 的逻辑向量.如果你只是想做一些事情,比如用氧"替换所有出现的氮",这应该就足够了

Depending on what you want to do you might not even need the 'which' as varnames == "nitrogen" gives a logical vector of TRUE/FALSE. If you just want to do something like replace all of the occurances of "nitrogen" with "oxygen" this should suffice

varnames[varnames == "nitrogen"] <- "oxygen"

这篇关于如何准确地grep一个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆