[英]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.