Reputation: 422
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
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