[R] Determine the Length of the Longest Word in a String
kingsfordjones at gmail.com
Fri Apr 10 23:23:40 CEST 2009
On Fri, Apr 10, 2009 at 2:40 PM, Shadley Thomas
<shadley.thomas at gmail.com> wrote:
> My question --
> It seems inefficient to determine which element is the longest and then
> calculate the length of that longest element. I was hoping to find a way to
> simply return the length of the longest word in a more straightforward way.
> Short sample code --
>> shadstr <- c("My string of words with varying lengths. Longest word is
> nine - 1 22 333 999999999 4444")
>> shadvector <- unlist(strsplit(shadstr, split=" "))
nchar is vectorized, so at this point you can just do
>> shadvlength <- lapply(shadvector,nchar)
>> shadmaxind <- which.max(shadvlength) ## Maximum element
>> shadmax <- nchar(shadvector[shadmaxind])
>  9
> Many thanks for your help and suggestions.
> [[alternative HTML version deleted]]
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help