Serhii
Serhii

Reputation: 422

Get the longest item from each element of the list

I have a list:

 a = c("aaaa", "bbbbbbb")
 b = c("a1", "b2", "c33")
 c = "d"
 d = list(a, b, c)

How can I get the longest items from each element of the list without a loop? In other words the goal is to obtain:

"bbbbbbb" "c33" "d"

I know how to calculate number of characters:

lapply(d, nchar)
[[1]]
[1] 4 7

[[2]]
[1] 2 2 3

[[3]]
[1] 1

I know how to find position of longest items:

lapply(lapply(d, nchar), which.max)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 1

But cannot find a way to select items.

I also considered sorting items by number of characters (nchar) in order to select all 1st items by lapply(d, "[[", 1). But without success.

Any help is much appreciated!

Upvotes: 2

Views: 735

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99351

You can put it all into an anonymous function. And we can use sapply() since you want an atomic result.

sapply(d, function(x) x[which.max(nchar(x))])
# [1] "bbbbbbb" "c33"     "d"    

Upvotes: 3

Related Questions