[英]gsub across each row of multiple columns of dataframe 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的第一个元素作为模式。
感谢任何输入以获得结果
谢谢!
我们可以将'Col2'中的元素paste
在一起,在gsub
中将其用作pattern
,在替换中使用''
,并用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"
尝试使用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 "
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.