How to check if a string contains only one type of character in R?


If a string contains more than one character then all of them could be same or different. If we want to check if a string contains only one type of character, then stri_count_fixed function of stringi package will be used with nchar function.

Check out the below given examples to understand how it can be done.

Example 1

Following snippet creates a sample data frame −

Countries<-sample(c("India","USA","UK","SSS"),20,replace=TRUE)
df1<-data.frame(Countries)
df1

The following dataframe is created −

  Countries
1  USA
2  India
3  India
4  SSS
5  USA
6  USA
7  USA
8  USA
9  India
10 SSS
11 SSS
12 India
13 SSS
14 USA
15 India
16 USA
17 SSS
18 USA
19 SSS
20 USA

To load stringi package and check whether all characters in each element of Countries is of one type or not, add the following code to the above snippet −

library(stringi)
df1$All_S<-stri_count_fixed(df1$Countries,"S")==nchar(df1$Countries)
df1

Output

If you execute all the above given snippets as a single program, it generates the following output: −

  Countries All_S
1  USA      FALSE
2  India    FALSE
3  India    FALSE
4  SSS      TRUE
5  USA      FALSE
6  USA      FALSE
7  USA      FALSE
8  USA      FALSE
9  India    FALSE
10 SSS      TRUE
11 SSS      TRUE
12 India    FALSE
13 SSS      TRUE
14 USA      FALSE
15 India    FALSE
16 USA      FALSE
17 SSS      TRUE
18 USA      FALSE
19 SSS      TRUE
20 USA      FALSE

Example 2

Following snippet creates a sample data frame −

Group<-sample(c("Control","Mixed","Common","XX"),20,replace=TRUE)
df2<-data.frame(Group)
df2

The following dataframe is created −

   Group
1  Mixed
2  XX
3  XX
4  Control
5  Mixed
6  Common
7  Common
8  Mixed
9  Mixed
10 XX
11 Mixed
12 Common
13 Common
14 XX
15 Mixed
16 Control
17 Mixed
18 Common
19 Control
20 Control

To check whether all characters in each element of Group is of one type or not, add the following code to the above snippet −

df2$All_X<-stri_count_fixed(df2$Group,"X")==nchar(df2$Group)
df2

Output

If you execute all the above given snippets as a single program, it generates the following output: −

   Group    All_X
1  Mixed    FALSE
2  XX       TRUE
3  XX       TRUE
4  Control  FALSE
5  Mixed    FALSE
6  Common   FALSE
7  Common   FALSE
8  Mixed    FALSE
9  Mixed    FALSE
10 XX       TRUE
11 Mixed    FALSE
12 Common   FALSE
13 Common   FALSE
14 XX       TRUE
15 Mixed    FALSE
16 Control  FALSE
17 Mixed    FALSE
18 Common   FALSE
19 Control  FALSE
20 Control  FALSE

Updated on: 10-Nov-2021

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements