Reputation: 19395
Consider this example
list('test', 'one')
I would like to subset this list and only keep the longest string in the list. Using purrr::keep
does not seem to work.
> list('test', 'one') %>% keep(~ nchar(.x) == max(nchar(.)))
[[1]]
[1] "test"
[[2]]
[1] "one"
Any ideas? Thanks!
Upvotes: 2
Views: 95
Reputation: 48241
If l
is stored, then indeed base R seems best:
l <- list('test', 'one')
# If you want only the first one or there is a unique element
l[which.max(nchar(l))]
# [[1]]
# [1] "test"
# General
l[nchar(l) == max(nchar(l))]
# [[1]]
# [1] "test"
Now with keep
we may do
list('test', 'one') %>% keep(function(x) nchar(x) == max(nchar(.)))
# [[1]]
# [1] "test"
The issue appears to be that both .
and .x
are just individual elements of the list in ~ nchar(.x) == max(nchar(.))
.
Upvotes: 1
Reputation: 21739
You can do simple:
k <- list('test', 'one')
k[which.max(lapply(k, nchar))]
[[1]]
[1] "test"
Upvotes: 1