Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract all maximum length values in a character vector in R

Tags:

string

select

r

max

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?

like image 877
Qirohchan Avatar asked Sep 23 '14 17:09

Qirohchan


1 Answers

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"
like image 98
Carlos Cinelli Avatar answered Oct 19 '22 06:10

Carlos Cinelli