adam.888
adam.888

Reputation: 7846

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.

Upvotes: 0

Views: 2662

Answers (1)

effel
effel

Reputation: 1421

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"

Upvotes: 2

Related Questions