Home > Net >  how to return words with longest word in one vector R
how to return words with longest word in one vector R

Time:04-21

new account here, i just wondering, i have vector called words with contain many words, i just want to find out the longest word based on his length, so i consider using for loop nchar and if to find out the longest word

so after do some desk research, my code will be like this

get.longest.word <- function(words)
    {
    for (i in words){
        if(max(nchar(i)) {
            print(i)
        }
    }
           }

and it returns error

Error in parse(text = x, srcfile = src): <text>:4:26: unexpected '{'
3:     for (i in words){
4:         if(max(nchar(i)) {
                            ^
Traceback:

since im new in R, could you guys pls see my code and where the wrong at?

my vector after i use dput(head(words)) are like this

c("a", "able", "about", "absolute", "accept", "account")

CodePudding user response:

A simple approach might be, in base R:

x <- c("cat", "corn", "house")
x[nchar(x) == max(nchar(x))]  # [1] "house"

The above selects all indices of x whose length is equivalent to the max length. It will return ties in the event that two or more words have the same max length.

CodePudding user response:

We could use which with max(nchar())

words <- c("a", "able", "about", "absolute", "accept", "account")

words[which.max(nchar(words))]
[1] "absolute"

CodePudding user response:

Another base R option

v[order(-nchar(v))][1]
  •  Tags:  
  • r
  • Related