Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if string is in uppercase in R

Tags:

Is there simpler method to match regex pattern in its entirety? For example, to check if given string is uppercase the following 2 methods but seem too complex. Checking stringr I found no indication for simpler solution either.

Method 1:

isUpperMethod1 <- function(s) {   return (all(grepl("[[:upper:]]", strsplit(s, "")[[1]]))) } 

Method 2:

isUpperMethod2 <- function(s) {   m = regexpr("[[:upper:]]+", s)   return (regmatches(s, m) == s) } 

I intentionally omit handling of empty, NA, NULL strings to avoid bloated code.

The uppercase pattern can be generalized to arbitrarily regex pattern (or character set).

I see no problems with both solutions above except that they seem excessively complex for the problem solved.

like image 921
topchef Avatar asked Feb 24 '14 15:02

topchef


People also ask

How do I check if a string has uppercase?

To check if a letter in a string is uppercase or lowercase use the toUpperCase() method to convert the letter to uppercase and compare it to itself. If the comparison returns true , then the letter is uppercase, otherwise it's lowercase. Copied!

Is lowercase in R?

tolower() method in R programming is used to convert the uppercase letters of string to lowercase string. Return: Returns the lowercase string.

What is Toupper function in R?

toupper() method in R programming is used to convert the lowercase string to uppercase string. Syntax: toupper(s) Return: Returns the uppercase string.

Do capitals matter in R?

There should be no difference.


1 Answers

You can use the ^ and $ patterns to match the beginning and end of the string

grepl("^[[:upper:]]+$", s) 
like image 174
Matthew Plourde Avatar answered Sep 26 '22 01:09

Matthew Plourde