简体   繁体   English

我如何 select 来自向量列表中每个字符串向量的最长字符串?

[英]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.我尝试了一些 sapply 和 nchar 的组合,但似乎无法弄清楚。 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.我对 R 很陌生,所以任何建议都会有很大帮助。 Thank you.谢谢你。

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"

Below will handle cases when two strings have same length and are max-length:下面将处理两个字符串长度相同且为最大长度的情况:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将存储在向量中的所有字符串粘贴到单个字符串中,这适用于列表中的每个字符串向量 - Paste all strings stored in a vector into a single string, this for each string vectors in a list 如何在向量列表上应用索引向量? - How do I apply an index vector over a list of vectors? 如何在满足条件时将向量拆分为向量列表? - How do I split a vector into a list of vectors when a condition is met? 我如何解决以下错误?输入必须是任意长度的字符向量或字符向量列表,每个字符向量的长度为1 - How do I solve the following error?Input must be a character vector of any length or a list of character vectors, each of which has a length of 1 如何解决:输入必须是任意长度的字符向量或字符向量列表,每个字符向量的长度为1 - How do I solve : Input must be a character vector of any length or a list of character vectors, each of which has a length of 1 在向量列表中,将每个向量转换为字符串,然后转换为R中的数据帧 - Within a list of vectors, convert each vector to a string then convert to dataframe in R 我如何 output 一个矩阵向量或 dataframe ,其中每个元素都是从每一行连接的字符串? - How do I output one vector for a matrix or dataframe in which each element is a string concatenated from each row? 如何从向量列表中获取 select 列? - How can I select columns from a vectors list? 如何从R中列表的每个向量中选择项目 - How to select items from each vector of the list in R 如何从R中的向量列表中创建矩阵? - How do I make a matrix from a list of vectors in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM