在字符串内容上创建新变量

时间:2013-02-12 13:30:55

标签: regex r

如果我有这些字符串:

dat <- data.frame(xxs = c("PElookx.PElookxstd","POaftGx.POlookGxstd"))

如何创建新变量,例如,如果字符串包含PE我想要NOWPO我会得到LATER

newxxs <- (`NOW`,`LATER`)

我知道如何使用grep来做到这一点:

dat$newxss <- NA
dat$newxss[grep("PE",dat$xxs)] <- "NOW"
dat$newxss[grep("PO",dat$xxs)] <- "LATER"

是否有比grep更多的方法?因为我必须为同一个新列和许多新列的多个字符串执行此操作。

2 个答案:

答案 0 :(得分:3)

如果您要进行不同的替换,可以创建一个自定义函数来同时执行所有替换,例如:

subst <- function(var, corresp) {
  sapply(corresp, function(elem) {
    var[grep(elem[1],var)] <- elem[2]
  })
}

var <- c("PEfoo", "PObar", "PAfoofoo", "PUbarbar")
corresp <- list(c("PE","NOW"),
                c("PO","LATER"),
                c("PA", "MAYBE"),
                c("PU", "THE IPHONE IS IN THE BLENDER"))
subst(var, corresp)

会给:

[1] "NOW"                          "LATER"                       
[3] "MAYBE"                        "THE IPHONE IS IN THE BLENDER"

因此,您可以重复将函数应用于数据框的不同列:

dat$new1 <- subst(dat$old1, corresp1)
dat$new2 <- subst(dat$old2, corresp2)
dat$new3 <- subst(dat$old3, corresp3)
...

答案 1 :(得分:2)

如果您的所有字符串绝对中包含PEPO,则可以使用ifelse

ifelse(grepl("PE", dat$xxs), "NOW", "LATER")

示例:

set.seed(45)

x <- sample(c("PEx", "POy"), 20, replace=T)
# [1] "POy" "PEx" "PEx" "PEx" "PEx" "PEx" "PEx" "POy" "PEx" "PEx" 
#         "PEx" "POy" "PEx" "PEx" "PEx" "PEx" "POy" "PEx" "PEx" "PEx"

ifelse(grepl("PE", x), "NOW", "LATER")

# [1] "LATER" "NOW"   "NOW"   "NOW"   "NOW"   "NOW"   "NOW"   "LATER" "NOW"   
#         "NOW"   "NOW"   "LATER" "NOW"   "NOW"   "NOW"  
# [16] "NOW"   "LATER" "NOW"   "NOW"   "NOW"