Package: stringr


Function: str_length()


1. Count the length of item1

Review the data (d11)

# A tibble: 4 x 2
     id item1
  <dbl> <chr>
1     1 "cap"
2     2 "ap" 
3     3 ""   
4     4 "p"  

In this data, item1 represents student responses of a word. Each letter represents a correct phonetic sound. We want to count the number of correct sounds for each student.

We first create a new variable item1_score using dplyr::mutate(). We can then use stringr::str_length() to count the length of our strings.

d11 %>%
  dplyr::mutate(item1_score = stringr::str_length(item1))
# A tibble: 4 x 3
     id item1 item1_score
  <dbl> <chr>       <int>
1     1 "cap"           3
2     2 "ap"            2
3     3 ""              0
4     4 "p"             1



Function: str_count()


1. Count the number of letters in item1

Review the data (d12)

# A tibble: 4 x 2
     id item1  
  <dbl> <chr>  
1     1 "c,a,p"
2     2 "a,p"  
3     3 ""     
4     4 "p"    

Same as above, item1 represents student responses of a word. Each letter represents a correct phonetic sound. We want to count the number of correct sounds for each student. However, this time, our data has commas between letters so we cannot use stringr::str_length() because it will count the commas, giving us incorrect scores.

Instead we use stringr::str_count() and add the argument pattern = and we add the regex pattern “[a-z]” which says to count any lowercase letter a to z.

d12 %>%
  dplyr::mutate(item1_score = stringr::str_count(item1, pattern = "[a-z]"))
# A tibble: 4 x 3
     id item1   item1_score
  <dbl> <chr>         <int>
1     1 "c,a,p"           3
2     2 "a,p"             2
3     3 ""                0
4     4 "p"               1

Return to Strings