jstewar9
jstewar9

Reputation: 95

R - Filter List Using First Element of Each Item in the List

I'm fairly new to R and I'm trying to parse data from a PDF into a data table. I've been able to parse the text into a list, but I'm having a hard time trying to filter data from the list.

As an example, consider the sample list below:

l_vectors <- list( c("K", "10", "20"),
                   c("1", "30", "40"),
                   c("a", "b", "c"),
                   c("x", "y", "z"))

Let's say I'd like to filter this list so it only includes the vectors starting with "K" or "1"

I can use map_lgl to find get a logical vector indicating which list items are a match

map_lgl(l_vectors, function(x) x[1] == "K" | x[1] == "1" )
[1]  TRUE  TRUE FALSE FALSE

From hear I'm not quite sure the best direction. I'm guessing that I'd want to use this logical vector in combination with pluck, but can't seem to figure it out. Any help would be appreciated!

Cheers, Jonathon

Upvotes: 5

Views: 733

Answers (2)

akrun
akrun

Reputation: 887241

An option is keep to loop over the list of vectors and create a logical vector of length 1 with str_detect wrapped with any. Here the pattern checked is the character "K" or (|) "1" from the start (^) of the string

library(purrr)
library(stringr)
keep(l_vectors, ~ any(str_detect(.x, "^(K|1)")))
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"

If we check only the first element, no need for any to be wrapped

keep(l_vectors, ~ str_detect(.x[1], "^(K|1)"))
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"

If it is a fixed match, then as in @markus post, can use %in%

keep(l_vectors,  ~ .x[1] %in% c("K", "1"))

Upvotes: 1

markus
markus

Reputation: 26343

If you want to use baseR you can write a helper function and then use Filter

f <- function(x) x[1] %in% c("K", "1")
Filter(f, l_vectors)
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"

This could also be written as

Filter(function(x) x[1] %in% c("K", "1"), l_vectors)

Upvotes: 3

Related Questions