【问题标题】:Delete rows if one column entry of a dataframe is a substring of another column entry如果数据框的一个列条目是另一列条目的子字符串,则删除行
【发布时间】:2013-08-15 18:36:26
【问题描述】:

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

【问题讨论】:

  • 请与您想要测试的行类型和想要获得的结果共享一个最小数据集。
  • 对不起!!我现在已经添加了数据集的开头以及我希望它之后的样子。

标签: r substring


【解决方案1】:

试试这个:

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

【讨论】:

  • 还有一个问题:你怎么知道这里需要使用mapply?我阅读了文档,但对于如何判断何时使用哪个应用功能感到非常困惑。
  • @user2631296 来自经验 :)
【解决方案2】:

最小数据集:

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)),]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2014-06-19
    • 2023-02-07
    • 1970-01-01
    相关资源
    最近更新 更多