簡體   English   中英

R:從列表中選擇元素

[英]R: selecting element from list

我有兩個要素:

id1 <- "dog"
id2 <- "cat"

我想從向量中提取這些元素的任何組合(dogcat或catddog)

L <- c("gdoaaa","gdobbb","gfoaaa","ghobbb","catdog")
L

我試過了:

L[grep(paste(id1,id2,sep="")),L]
L[grep(paste(id2,id1,sep="")),L]

但這會導致錯誤。

感謝您為糾正上述問題所提供的幫助。

錯誤是由於括號位置錯誤,因此代碼上的這些細微變化將起作用。

L[grep(paste(id1,id2,sep=""), L)]
# character(0)
L[grep(paste(id2,id1,sep=""), L)]
# [1] "catdog"

另外,這是一個正則表達式單線:

L[grep(paste0(id2, id1, "|", id1, id2), L)]
# [1] "catdog"

該注釋中的某些模式也將與dogcatt匹配。 為了避免這種情況,您可以這樣使用^$

x <- c("dogcat", "foo", "catdog", "ddogcatt")
x[grep(paste0("^", id2, id1, "|", id1, id2, "$"), x)]
# [1] "dogcat" "catdog"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM