-1

必须是一种避免在 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”等效项。谢谢。

4

2 回答 2

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
于 2012-04-11T21:25:45.970 回答
0

这是一个使用gsubfn包的选项,这将用“A”替换任何带有“A”的单词,“E”也是如此,任何带有“I”,“O”或“U”的单词都将是替换为“IOU”,任何小写元音都将使用“other”进行替换(这将替换整个字符串,这似乎是所要求的,如果需要其他内容可以修改):

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)
于 2012-04-12T19:14:49.493 回答