gsub跨越多列数据帧R的每一行

时间:2016-02-25 07:52:50

标签: regex r

我有一个示例数据框,如下所示:

dat1 <- data.frame(Col1= c("a woman's hat 9 in. long", "ABC company news", "P.F.Chang's house", "this would weigh 90 lbs."),
Col2= c("9 in.", "ABC", "P.F.Chang's", "90 lbs."),
stringsAsFactors=F)

dat1
                      Col1        Col2
1 a woman's hat 9 in. long       9 in.
2         ABC company news         ABC
3        P.F.Chang's house P.F.Chang's
4 this would weigh 90 lbs.     90 lbs.

我想删除与数据框的col2匹配的col1部分。所以,我希望结果如下:

                Col1        Col2
1 a woman's hat long       9 in.
2       company news         ABC
3              house P.F.Chang's
4   this would weigh     90 lbs.

我试过了gsub(dat1$col2, '', dat1$col1)。但是,这只会使用dat1 $ col2的第一个元素作为模式。

感谢任何输入以获得结果

谢谢!

2 个答案:

答案 0 :(得分:4)

我们可以paste将'Col2'中的元素组合在一起,将其用作pattern中的gsub,替换我们使用'',并删除领先/滞后trimws的空格。

dat1$col1 <- trimws(gsub(paste(dat1$Col2, collapse='|'), 
                '', dat1$Col1))
dat1$col1
#[1] "a woman's hat  long" "company news"        "house"               "this would weigh"   

我们也可以使用stri_replace

library(stringi)
stri_trim(stri_replace(dat1$Col1, fixed=dat1$Col2, ""))
#[1] "a woman's hat  long" "company news"        "house"               "this would weigh"   

更紧凑的方法是

library(qdap)
with(dat1, mgsub(Col2, '', Col1))
#[1] "a woman's hat long" "company news"       "house"              "this would weigh"  

答案 1 :(得分:4)

尝试使用stringr包,以及 Nicola 建议的修改 - fixed(dat1$col2)

library(stringr)
str_replace(dat1$Col1, fixed(dat1$Col2), "")

"a woman's hat  long" " company news"       " house"              "this would weigh "  
>