How to search for multiple strings and replace the

2020-05-26 11:51发布

I have a column in a dataframe like this:

npt2$name
#  [1] "Andreas Groll, M.D."
#  [2] ""
#  [3] "Pan-Chyr Yang, PHD"
#  [4] "Suh-Fang Jeng, Sc.D"
#  [5] "Mostafa K Mohamed Fontanet Arnaud"
#  [6] "Thomas Jozefiak, M.D."
#  [7] "Medical Monitor"
#  [8] "Qi Zhu, MD"
#  [9] "Holly Posner"
# [10] "Peter S Sebel, MB BS, PhD Chantal Kerssens, PhD"
# [11] "Lance A Mynderse, M.D."
# [12] "Lawrence Currie, MD"

I tried gsub but with no luck. After doing toupper(x) I need to replace all instances of 'MD' or 'M.D.' or 'PHD' with nothing.

Is there a nice short trick to do it?

In fact I would be interested to see it done on a single string and how differently it is done in one command on the whole list.

标签: string r
3条回答
放我归山
2楼-- · 2020-05-26 12:04

Here's a variant that removes the extra ", " too. Does not require touppper either - but if you want that, just specify ignore.case=TRUE to gsub.

test <- c("Andreas Groll, M.D.", 
  "",
  "Pan-Chyr Yang, PHD",
  "Suh-Fang Jeng, Sc.D",
  "Peter S Sebel, MB BS, PhD Chantal Kerssens, PhD",
  "Lawrence Currie, MD")

gsub(",? *(MD|M\\.D\\.|P[hH]D)", "", test)
#[1] "Andreas Groll"                         ""                                     
#[3] "Pan-Chyr Yang"                         "Suh-Fang Jeng, Sc.D"                  
#[5] "Peter S Sebel, MB BS Chantal Kerssens" "Lawrence Currie"
查看更多
对你真心纯属浪费
3楼-- · 2020-05-26 12:07

With a single ugly regex:

 gsub('[M,P].?D.?','',npt2$name)

Which says, find characters M or P followed by zero or one character of any kind, followed by a D and zero or one additional character. More explicitly, you could do this in three steps:

npt2$name <- gsub('MD','',npt2$name)
npt2$name <- gsub('M\\.D\\.','',npt2$name)
npt2$name <- gsub('PhD','',npt2name)

In those three, what's happening should be more straight forward. the second replacement you need to "escape" the period since its a special character.

查看更多
一夜七次
4楼-- · 2020-05-26 12:10

Either of these:

gsub("MD|M\\.D\\.|PHD", "", test)  # target specific strings
gsub("\\,.+$", "", test)        # target all characters after comma

Both Matt Parker above and Tommy below have raised the question whether 'M.R.C.P.', 'PhD', 'D.Phil.' and 'Ph.D.' or other British or Continental designations of doctorate level degrees should be sought out and removed. Perhaps @user56 can advise what the intent was.

查看更多
登录 后发表回答