[英]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.