我想在 R 中有一个函数,它可以在给定的子字符串(例如“alpha”)周围插入点(“.”),如果它们不存在的话。例如。
string="10-alpha-epoxy-Amorph-4-ene"
应该返回
"10-.alpha.-epoxy-Amorph-4-ene"
string="alpha-cadolene"
应该返回
".alpha.-cadolene"
但是
string=".alpha.-cadolene"
应该返回
".alpha.-cadolene"
(子串可以出现多次)
在 R 中使用 gsub 最简单的方法是什么?
干杯,汤姆
最佳答案
我会做这样的事情:
gsub("[.]?(alpha)[.]?", ".\\1.", c("10-alpha-epoxy-Amorph-4-ene",
".alpha.-cadolene", "alpha.-cadolene",
".alpha-cadolene"
))
[1] "10-.alpha.-epoxy-Amorph-4-ene" ".alpha.-cadolene"
".alpha.-cadolene" ".alpha.-cadolene"
编辑对许多术语的概括:
如果您有一个术语列表,您可以使用 paste
创建游览正则表达式:
terms <- c('alpha','gamma','beta','delta')
gsub(paste0("[.]?(",paste0(terms,collapse='|'),")[.]?"), ".\\1.",
c("10-alpha-epoxy-Amorph-4-ene",
".gamma.-cadolene", "beta.-cadolene",
".delta-cadolene"))
[1] "10-.alpha.-epoxy-Amorph-4-ene" ".gamma.-cadolene"
".beta.-cadolene"
[4] ".delta.-cadolene"
EDIT 获取全字母的 greels 列表:
library(XML)
dat <- readHTMLTable("http://en.wikipedia.org/wiki/Greek_alphabet",
strinsAsFactors=FALSE)[[2]]
terms <- as.character(dat$V2[-c(1,2)])
[1] "alpha" "beta" "gamma" "delta" "epsilon" "zeta" "eta" "theta" "iota" "kappa" "lambda"
[12] "mu" "Name" "Modern" "nu" "xi" "omicron" "pi" "rho" "sigma" "tau" "upsilon"
[23] "phi" "chi" "psi" "omega"
关于r - 在 R 中使用 gsub 在子字符串周围插入点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20925591/