Check if the Column Contains a String or not

Check if the Column Contains a String or not, The methods listed below can be used to determine whether a column of a data frame in R contains a string.

Let’s create a data frame first,

Check if the Column Contains a String or not

df <- data.frame(team=c('T1', 'T1', 'T1', 'T2', 'T2', 'T3'),
                 conf=c('East', 'East', 'South', 'West', 'West', 'East'),
                 points=c(101, 214, 215, 115, 214, 147))

Now we can view the data frame

df
  team  conf points
1   T1  East    101
2   T1  East    214
3   T1 South    215
4   T2  West    115
5   T2  West    214
6   T3  East    147

Example 1: See if the exact string is present in the column

The following code demonstrates how to determine whether the precise string “Eas” is present in the data frame’s conf column.

Now we can verify if the precise string “Eas” appears in the conf column

library(stringr)
sum(str_detect(df$conf, '^Eas$')) > 0
[1] FALSE

This informs us that the conf column does not contain the precise string “Eas.”

Note: To identify the start () and end ($) characters of the string we were looking for, we utilized the regex symbols.

Data Science in Banking and Finance » finnstats

Example 2: Check to See if a Partial String Exists in a Column

Run the following code to locate the partial string “Eas” in the data frame’s conf column:

Now we can check to see whether conf column has the partial string “Eas”

sum(str_detect(df$conf, 'Eas')) > 0
[1] TRUE

This demonstrates that the data frame’s conf column does contain the partial string “Eas.”

Example 3: Count Partial String Occurrences in Column

The partial text “Eas” may be found in the data frame’s “conf” column, and the following code demonstrates how to count its occurrences there:

Let’s count instances of the conf column’s partial string “Eas”

sum(str_detect(df$conf, 'Eas'))
[1] 3

This indicates that the data frame’s conf column contains the partial string “Eas” three times.

Calculate Confidence Intervals in R » finnstats

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

4 + nine =