[英]R: Delete element from multiple vectors if only present in a few vectors
如果多個矢量中僅包含幾個元素,該如何刪除它們。 例如,如果我有以下兩個向量
> Text <- c("AB.txt", "B.txt", "C.txt")
> Text2 <- c("B.txt", "C.txt")
然后我嘗試使用grep刪除所有帶有'A'的元素:
> Text[-grep( “A”, Text)]
[1] "B.txt" "C.txt"
但是,當我在Text2上執行此操作時,所有元素都會消失在網絡空間中。
> Text2[-grep( “A”, Text2)]
character(0)
如何更改代碼,使其適用於所有矢量?
提前致謝,
保羅
您可以使用invert
參數:
Text[grep("A", Text, fixed = TRUE, invert = TRUE)]
#[1] "B.txt" "C.txt"
Text2[grep("A", Text2, fixed = TRUE, invert = TRUE)]
#[1] "B.txt" "C.txt"
如果查看一下grep("A", Text2)
實際返回的內容:
grep("A", Text2)
# integer(0)
也就是說,它在Text2
找不到'A'。 因此,您的Text2[-integer(0)]
將不會返回任何內容
您可以使用grepl
來測試字符是否存在(或在這種情況下不使用!
)
Text[!grepl("A", Text)]
# [1] "B.txt" "C.txt"
Text2[!grepl("A", Text2)]
# [1] "B.txt" "C.txt"
在此,如果字符/樣式匹配,則grepl
返回邏輯值。 在此示例中,對於Text2
,在任何一個元素中均未找到“ A”
grepl("A", Text2)
# [1] FALSE FALSE
因此,現在我們可以“取反”它,並對原始向量進行子集化,這與進行Text2[!c(FALSE, FALSE)]
一種選擇是確定我們要保留的Text2
中的索引。 這是所有未出現在grep
輸出中的索引。
Text2[!c(1:length(Text2)) %in% grep("A", Text2)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.