如何将 gsub 应用于确切的单词而不是字符

How to apply gsub on exact words instead of characters

我在 R 中有一个数据框,其中包含一列 "CountryCode"。

我想要 select 个有效国家并将所有其他代码替换为 "OtherCountry"。所以我写道:

Valid_Countries <- c("US", "CA", "JP", "AU", "DE", "IT", "ES", "FR", "UK", "FI", "SE", "NO")

levels(Orders2$CountryCode) <- gsub(paste0("[^", paste(Valid_Countries, collapse=""), "]+"), "OtherCountry", levels(Orders2$CountryCode))

几乎有效。我的问题是 "BE" 之类的国家/地区代码被替换为 "OtherCountryE"(我猜这是因为 "E" 包含在 Valid_Countries 中)。

我怎么说"just consider the entire code"?

这个有用吗:

levels(Orders2$CountryCode)[
    !(levels(Orders2$CountryCode) %in% Valid_Countries)
    ] <- "OtherCountry