如何用R中的空格替换多个单词?

时间:2019-04-10 19:20:34

标签: r

这里是一个例子:

drugs<-c("Lapatinib-Ditosylate", "Caffeic-Acid-Phenethyl-Ester", "Pazopanib-HCl", "D-Pantethine")

ads<-"These are recently new released drugs Lapatinib Ditosylate, Pazopanib HCl, and Caffeic Acid Phenethyl Ester"

我想要的是用ads中的名称更正drugs中的药物名称,以使所需的输出为:

"These are recently new released drugs Lapatinib-Ditosylate, Pazopanib-HCl, and Caffeic-Acid-Phenethyl-Ester"

2 个答案:

答案 0 :(得分:2)

如果创建一个要替换的单词向量,则可以在该向量和单词向量上进行循环以替换它们(drugs),从而在循环的每个交互中替换一个元素的所有实例。

to_repl <- gsub('-', ' ', drugs)

for(i in seq_along(drugs))
  ads <- gsub(to_repl[i], drugs[i], ads)

ads
# "These are recently new released drugs Lapatinib-Ditosylate, Pazopanib-HCl, and Caffeic-Acid-Phenethyl-Ester"

与普遍看法相反,R中的for循环并不比lapply

f_lapply <- function(ads){
  to_repl <- gsub('-', ' ', drugs)
  invisible(lapply(seq_along(to_repl), function(i) {
    ads <<- gsub(to_repl[i], drugs[i], ads)
  }))
  ads
}
f_loop <- function(ads){
  to_repl <- gsub('-', ' ', drugs)
  for(i in seq_along(to_repl))
    ads <- gsub(to_repl[i], drugs[i], ads)
  ads
}

f_loop(ads) == f_lapply(ads)
# [1] TRUE

microbenchmark::microbenchmark(f_loop(ads), f_lapply(ads), times = 1e4)
# Unit: microseconds
#           expr    min      lq     mean  median      uq       max neval
#    f_loop(ads) 59.488  95.180 118.0793 107.487 120.205  7426.866 10000
#  f_lapply(ads) 69.333 114.462 147.9732 130.872 152.205 27283.670 10000

或者,使用更一般的示例:

loop_over <- 1:1e5
microbenchmark::microbenchmark(
  for_loop = {for(i in loop_over) 1},
  lapply   = {lapply(loop_over, function(x) 1)}
  )
# Unit: milliseconds
#      expr      min         lq       mean     median         uq       max neval
#  for_loop  4.66174   5.865842   7.725975   6.354867   7.449429  35.26807   100
#    lapply 94.09223 114.378778 125.149863 124.665128 134.217326 170.16889   100

loop_over <- 1:1e5
microbenchmark::microbenchmark(
  for_loop = {y <- numeric(1e5); for(i in seq_along(loop_over)) y[i] <- loop_over[i]},
  lapply   = {lapply(loop_over, function(x) x)}
  )
# Unit: milliseconds
#      expr      min       lq     mean   median       uq     max neval
#  for_loop 11.00184 11.49455 15.24015 12.10461 15.26050 134.139   100
#    lapply 71.41820 81.14660 93.64569 87.05162 98.59295 357.219   100

答案 1 :(得分:0)

这也可以使用(::after)来完成,它比lapply()循环快。修改@IceCreamToucan的答案,可以在for中进行如下操作

lapply

微基准测试

to_repl <- gsub('-', ' ', drugs)

invisible(lapply(seq_along(to_repl), function(i) {
  ads <<- gsub(to_repl[i], drugs[i], ads)
}))

# [1] "These are recently new released drugs Lapatinib-Ditosylate, Pazopanib-HCl, and Caffeic-Acid-Phenethyl-Ester"