R映射相当于?

时间:2012-04-11 20:06:10

标签: regex r

必须是一种避免在R中执行此操作的方法。某种映射函数?基本上,想要指定一系列grepl条件和一系列替换。谢谢,

hold[grepl('TRAVEL', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "TRAVEL"
hold[grepl('IN-KIND:', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "IN-KIND"
hold[grepl('COMPLIANCE', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "COMPLIANCE"
hold[grepl('MEDIA', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "MEDIA"
hold[grepl('WATER|FOOD|OFFICE|Office|CLEANING|ALARM', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "OFFICE"
hold[grepl('DATA', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "DATA"
hold[grepl('LEGAL', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "LEGAL"
hold[grepl('EVENT', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "EVENT"
hold[grepl('CATERING', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "CATERING"
hold[grepl('PHONE', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "PHONE"
hold[grepl('EQUIPMENT', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "EQUIPMENT"
hold[grepl('FUNDRAISING|FINANCE', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "FUNDRAISING"
hold[grepl('PAYROLL', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "PAYROLL"
hold[grepl('LIST RENTAL', hold[, "exp_pur_desc"]), "exp_pur_desc"] <- "LIST RENTAL"

编辑:是的,对不起,小小的轻浮。 hold是data.frame,其中一列名为“exp_pur_desc”。我可以看到lapply或sapply使用“switch”等效。感谢。

2 个答案:

答案 0 :(得分:1)

这是一种方式:

strReplace <- function(x, mapFrom, mapTo) {
    for (i in seq_along(mapFrom)) {
        x <- gsub(mapFrom[[i]], mapTo[[i]], x)
    }
    x
}

strReplace(c("Hello cruel world!", "Hello again Tellus!"), # Text
           c("Hello", "world|Tellus"), # words to replace (regular expressions)
           c("Hi", "moon"))            # words to replace with
#[1] "Hi cruel moon!" "Hi again moon!"

......所以在你的情况下:

hold<-data.frame(ID=11:12, exp_pur_desc=c('FOOD','FINANCE'))
hold[['exp_pur_desc']] <- strReplace(hold[['exp_pur_desc']],
  c('WATER|FOOD|OFFICE|Office|CLEANING|ALARM', 'FUNDRAISING|FINANCE'),
  c('OFFICE', 'FUNDRAISING'))
hold

答案 1 :(得分:0)

这是一个使用gsubfn包的选项,这将用&#34; A&#34;替换任何单词。仅使用&#34; A&#34;,对于&#34; E&#34;,任何使用&#34; I&#34;,&#34; O&#34;或&#34; U&#34;将由&#34; IOU&#34;取代任何小写元音都会使用&#34;其他&#34;替换(这取代了整个字符串,这似乎是要求的,如果需要其他东西,它可以被修改):

library(gsubfn)

replacements <- list(A='A', E='E', I='IOU', O='IOU', U='IOU', 'other')

gsubfn('^.*?(A|E|I|O|U|a|e|i|o|u).*$', replacements, state.name)