Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R string containing only one type of character

Tags:

r

stringr

I would like to check if a string contain only one type of character

For example

INPUT: 

str = "AAAAB"
char = "A"

OUTPUT:

str contains only char = FALSE

With grepl(char,str) the result is TRUE but I want it to be FALSE.

Many thanks

like image 561
user3910073 Avatar asked Aug 06 '14 11:08

user3910073


People also ask

How to check if string contains certain characters in R?

How to Check if string contains certain characters in R. To check if a string contains certain characters or not, we can use the grepl () function in R language. R Programming A-Z: R For Data Science With Real Exercises! Here is an example that checks the ll characters in the Hello string.

Where is B in a string in R?

Based on the previous output of the RStudio console we can see that the character “B” is located at the positions 15 and 25 within our character string x. The R programming language provides many alternative codes for the location of characters within strings.

Which class of an object holds character strings in R?

The class of an object that holds character strings in R is “character”. A string in R can be created using single quotes or double quotes. chr = 'this is a string' chr = "this is a string" chr = "this 'is' valid" chr = 'this "is" valid' We can create an empty string with empty_str = "" or an empty character vector with empty_chr = character (0).

How to convert non-character objects to character strings in R?

The functions as.character () and is.character () can be used to convert non-character objects into character strings and to test if a object is of type “character”, respectively. R has five main types of objects to store data: vector, factor, multi-dimensional array, data.frame and list.


2 Answers

If you want to check for a specific character (in char):

str <- "AAAAB"
char = "A"
all(unlist(strsplit(str, "")) == char)
#[1] FALSE

str <- "AAAA"
char = "A"
all(unlist(strsplit(str, "")) == char)
#[1] TRUE

Or, if you want to check if the string contains only one unique character (any one):

str <- "AAAAB"
length(unique(unlist(strsplit(str, "")))) == 1
#[1] FALSE

str = "AAAA"
length(unique(unlist(strsplit(str, "")))) == 1
#[1] TRUE
like image 63
talat Avatar answered Oct 06 '22 03:10

talat


You need to use not operator for regex, in your case this would be:

> !grepl("[^A]", "AAA")
[1] TRUE
> !grepl("[^A]", "AAAB")
[1] FALSE

With variables:

grepl(paste0("[^", char, "]"), srt)
like image 27
m0nhawk Avatar answered Oct 06 '22 02:10

m0nhawk