假設我有以下字串 -
vector <- "this is a string of text containing stuff. something.com [email protected] and other stuff with something.anything"
如果字串包含@or .,我想洗掉它,所以我想洗掉something.com,[email protected]和something.anything。我不想洗掉stuff,因為它是句末并且不包含.. 理想情況下,我希望能夠使用%>%管道來做到這一點。
uj5u.com熱心網友回復:
(更簡潔/簡單)方法的替代gsub方法:
gre <- gregexpr("[^ ] [.@][^ ] ", vector)
regmatches(vector, gre)
# [[1]]
# [1] "something.com" "[email protected]" "something.anything"
regmatches(vector, gre) <- ""
vector
# [1] "this is a string of text containing stuff. and other stuff with "
這樣做的好處是可以任意更換。當然,我們只是在這里用 替換它們"",所以這有點矯枉過正,但是如果您需要以某種方式更改值(更改每個子字串),那么這是一種更強大的機制。
uj5u.com熱心網友回復:
gsub(" ?\\w [.@]\\S ", "", vector)
[1] "this is a string of text containing stuff. and other stuff with"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476793.html
