正则表达式grep-parsing来自2个变量

时间:2015-09-25 13:46:21

标签: regex r grep grepl

目的是在清理数据集时折叠/重新分配级别。

以下是示例:

df <- data.frame(V1 <- c("cat","lion","cat","beast","cat"),
             V2 <- c("nice and grumpy","angry","old,but also nice","empty","has friends"),
             stringsAsFactors = F); colnames(df) <- c("V1","V2")
>df
     V1          V2
1   cat   nice and grumpy
2  lion             angry
3   cat   old,but also nice
4 beast             empty
5   cat       has friends

兴趣程度为cat;这些是条目:

parse1 <- V1[grepl("cat",V1)]
#[1] "cat" "cat" "cat"

从那里开始,想法是在V2nice中搜索属性,将cat级别重命名为nice cat。此搜索在V2中找到两个感兴趣的条目:

 df.sub <- subset(df,V1=="cat",select=V1:V2)
 parse2 <- df.sub$V2[grep("([Nn]ice)",df.sub$V2)]
#[1] "nice and grumpy"   "old,but also nice"

理想的最终结果将df转换为:

     V1                V2
1   nice cat   nice and grumpy
2   lion           king
3   nice cat   old,but also nice
4   beast           empty
5   cat        has friends

有任何想法如何实现这一目标?非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用data.table

df <- data.frame(V1 <- c("cat","lion","cat","beast","cat"),
         V2 <- c("nice and grumpy","angry","old,but also nice","empty","has friends"),
         stringsAsFactors = F); colnames(df) <- c("V1","V2")

library(data.table)
DT <- data.table(df)
# All the nice animals
DT[grepl ("([Nn]ice)",V2), V3:= paste0("nice ",V1)]
# All the nice cats
DT[grepl ("([Nn]ice)",V2) & V1=="cat", V4:= paste0("nice ",V1)]

答案 1 :(得分:1)

ifelse似乎就足够了:

df$V1 <- ifelse(grepl("([Nn]ice)", df$V2), 
                sub('cat', 'nice cat', df$V1), 
                df$V1 )

输出:

> df
        V1                V2
1 nice cat   nice and grumpy
2     lion             angry
3 nice cat old,but also nice
4    beast             empty
5      cat       has friends