在R中重新评估默认值

时间:2014-11-25 17:21:45

标签: r regex plyr

我使用Revalue包中的plyr函数重新分配长字符向量的名称,如下例所示:

sites <- c("example1.com","example2.com","facebook.com","google.com","example3.com")
replace <- c(facebook.com = "Facebook", google.com = "Google")
revalue(sites,replace)
# [1] "example1.com" "example2.com" "Facebook"     "Google"       "example3.com"

但是,我也想用&#34;其他&#34;替换所有的例子,所以我真正想要获得的是:

# [1] "other" "other" "Facebook"     "Google"       "other"

但我无法花时间在replace向量中包含每个网站。最好的方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

这是另一种选择

> sites <- gsub("\\.com$", "", sites)
> ifelse(sites %in% c("facebook", "google"), sites, "other")
[1] "other"    "other"    "facebook" "google"   "other"   

答案 1 :(得分:0)

您可以使用mapvalues()替换多个级别,然后使用revalue()替换单个级别:

library(dplyr)
library(plyr)
sites %>%
mapvalues(from=c("example1.com", "example2.com", "example3.com"), to=c(rep("other",3))) %>% 
revalue(replace)