0

我有一个包含两列 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
4

2 回答 2

0

最小数据集:

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)),]
于 2013-08-15T19:19:32.553 回答
0

尝试这个:

df[!mapply(grepl, df$V2, df$V1),]
于 2013-08-15T19:11:37.360 回答