randlom
randlom

Reputation: 13

How do I select the longest string from each vector of strings in a list of vectors?

I have a list of vectors that contain strings, and I am trying to get a list of vectors that only contain the single longest string in each vector.

Example:

What I have:

    [[1]]
    [1] "The quick brown fox"
    [2] "jumps over the"
    [3] "lazy dog"

    [[2]]
    [1] "She's a grand old flag"
    [2] "She's a high-flying flag"
    [3] "And forever in peace may she wave"

What I want:

    [[1]]
    [1] "The quick brown fox"

    [[2]]
    [1] "And forever in peace may she wave"

I've tried some combinations of sapply and nchar, but cannot seem to figure it out. I'm thinking I might need to write some sort of loop? I'm very new to R, so any advice will be a great help. Thank you.

Upvotes: 1

Views: 935

Answers (2)

ashwin agrawal
ashwin agrawal

Reputation: 1611

Below will handle cases when two strings have same length and are max-length:

lapply(yourList, function(x) x[nchar(x)==max(nchar(x))])

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40141

You can try:

lapply(lst, function(x) x[which.max(nchar(x))])

[[1]]
[1] "The quick brown fox"

[[2]]
[1] "And forever in peace may she wave"

Upvotes: 3

Related Questions