SDahm
SDahm

Reputation: 436

Select items of list of strings that contain certain characters

I' ve got a list of names.

l1 <- rep(paste("Session", 1:6, sep=""), each=4)
l2 <- rep(paste("ID", 1:4, sep=""), 6)
list <- paste(l1, l2, sep="")

With real data the list is far more complicated ;) How do create a new list from this list, that includes only those items from Session 1-4?

In dplyr there is the >>select(contains("Session1"|"Session2"))<< which is used to select variables in data.frames. I am looking for something similar to use for lists.

Upvotes: 2

Views: 6085

Answers (2)

akrun
akrun

Reputation: 887501

Here is another option with regex lookarounds to match "Session" followed by numbers 1-4 and not followed by any number ((?![0-9]))

grep("Session[1-4](?![0-9])", c(list, "Session10ID"), value = TRUE, perl = TRUE)
#[1] "Session1ID1" "Session1ID2" "Session1ID3" "Session1ID4" "Session2ID1" "Session2ID2" "Session2ID3" "Session2ID4" "Session3ID1" "Session3ID2"
#[11] "Session3ID3" "Session3ID4" "Session4ID1" "Session4ID2" "Session4ID3" "Session4ID4"

Upvotes: 0

joel.wilson
joel.wilson

Reputation: 8413

Is this what you want ?

list[grepl("Session(1|2|3|4)ID", list)]
[1] "Session1ID1" "Session1ID2" "Session1ID3" "Session1ID4" "Session2ID1" "Session2ID2" "Session2ID3" "Session2ID4"
[9] "Session3ID1" "Session3ID2" "Session3ID3" "Session3ID4" "Session4ID1" "Session4ID2" "Session4ID3" "Session4ID4"

Upvotes: 4

Related Questions