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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With