Qirohchan
Qirohchan

Reputation: 1137

Extract all maximum length values in a character vector in R

I have made a function, which basically outputs multiple length strings, i.e., for example,

"110110" "110"    "101"    "011" 

Now, I assigned the output of the function in a variable a,

a<- c("110110", "110",   "101",    "011")

The class of a comes out to be character. Now, I want only those strings which have the maximum length. For example, in this example, maximum length is of "110110" . So, I want that. I tried using max command, but it returns only one maximum length string if there are multiple. For example, in strings like these,

a <- c("110", "101", "abc", "cab")

Using max command returns only, "cab". However, I want all the maximum length strings. How can I do it?

Upvotes: 12

Views: 7967

Answers (1)

Carlos Cinelli
Carlos Cinelli

Reputation: 11607

To measure the "length" of the string you have to use something like nchar. If you want all the elements which have the maximum number of characters you can filter with nchar(a)==max(nchar(a)). The following code should do what you are trying to do:

a <- c("110", "101", "abc", "cab")

a[nchar(a)==max(nchar(a))]
[1] "110" "101" "abc" "cab"

Upvotes: 16

Related Questions