簡體   English   中英

我如何 select 來自向量列表中每個字符串向量的最長字符串?

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

我有一個包含字符串的向量列表,我正在嘗試獲取一個向量列表,該列表僅包含每個向量中最長的單個字符串。

例子:

我有的:

    [[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"

我想要的是:

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

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

我嘗試了一些 sapply 和 nchar 的組合,但似乎無法弄清楚。 我在想我可能需要編寫某種循環? 我對 R 很陌生,所以任何建議都會有很大幫助。 謝謝你。

你可以試試:

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

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

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

下面將處理兩個字符串長度相同且為最大長度的情況:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM