简体   繁体   中英

R: selecting element from list

I have two elements:

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

I want to extract any combination of these elements (dogcat or catddog) from a vector

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

I tried:

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

but this gives an error.

I would be grateful for your help in correcting the above.

The error is from misplaced parentheses, so these minor variations on your code will work.

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

Alternatively this is a regex one-liner:

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

That and some patterns in the comments will also match dogcatt . To avoid this you could use ^ and $ like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM