Hi Everyone,

I'm new to programming R and have accomplished my goal, but feel that there
is probably a more efficient way of coding this.  I'd appreciate any
guidance that a more advanced programmer can provide.

My goal --
I would like to find the length of the longest word in a string containing
many words separated by spaces.

How I did it --
I was able to find the length of the longest word by parsing the string into
a list of separate words, using the function "which.max" to determine the
element with the longest length, and then using "nchar" to calculate the
length of that particular word.

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=" "))
> shadvlength <- lapply(shadvector,nchar)
> shadmaxind <- which.max(shadvlength) ## Maximum element
> shadmax <- nchar(shadvector[shadmaxind])
> shadmax
[1] 9

Many thanks for your help and suggestions.
Shad

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to