繁体   English   中英

如果数据框的一个列条目是另一列条目的子字符串,则删除行

[英]Delete rows if one column entry of a dataframe is a substring of another column entry

我有一个数据框,其中有两列V1和V2,两列中都有诸如A1,A2,A1 + A2,A3之类的条目。

如果其中任一列包含其他子字符串,我想删除行。 因此,例如,我想删除这样的行:

A1, A1+A2

A1+A2,A1

但不是这样的行:

A1+A2, A3

我目前正在使用此代码:

subset(dat, !dat$V1 %in% dat$V2)

但是当我想保留这些行时,此代码摆脱了诸如A1 / B1,A2-B2和A 02,A4之类的行。

我想我可以使用charmatch,也许是这样的:

subset(dat, charmatch(dat$V1, dat$V2) == "NA")

但这会返回一个空的数据框。

当我运行以下代码来检查将删除哪些charmatch时:

trial <- subset(dat, charmatch(dat$V1, dat$V2) != "NA")

当我要保留这些行时,会出现诸如A1 / B1,A2-B2和A 02,A4之类的行。

我认为问题可能在于A 02带有空格,但不确定如何解决此问题。

我还考虑过使用grep / grepl和正则表达式,但是我不确定当我针对另一列搜索一列的表达式时,它在语法上的外观如何。 我将第一列转换为向量并使用:

subset(dat, !grepl(V1vector, dat$V2)) 

有任何想法吗?

这是一些数据集:

V1          V2
A3-B3   B3  
A4/B4   A3-B3   
A 28    A 05    
A 28    A 06    
A2-B2   A2  
B 05    B1  

这就是我想要的样子:

V1         V2
A4/B4      A3-B3
A 28       A 05
A 28       A 06
B 05       B1

尝试这个:

df[!mapply(grepl, df$V2, df$V1),]

最小数据集:

f <- structure(list(V1 = c("A3-B3", "A4/B4", "A 28", "A 28", "A2-B2", 
"B 05"), V2 = c("B3", "A3-B3", "A 05", "A 06", "A2", "B1")), .Names = c("V1", 
"V2"), row.names = c(NA, -6L), class = "data.frame")

##entries of V1 that contain V2
mapply(grepl, f$V2, f$V1, MoreArgs=list(fixed=TRUE)) 
##entries of V2 that contain V1
mapply(grepl, f$V1, f$V2, MoreArgs=list(fixed=TRUE))

##combine the two negations
f[!mapply(grepl, f$V2, f$V1, MoreArgs=list(fixed=TRUE)) & 
  !mapply(grepl, f$V1, f$V2, MoreArgs=list(fixed=TRUE)),]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM