Danny  Morris
Danny Morris

Reputation: 102

Is there a faster alternative to counting special characters for 100,000 short strings in R?

I am trying to count the number of non-alphanumeric characters for each string in a vector of 100,000 strings. I am finding my current implementation to be slower that I would like.

My current implementation uses purrr::map() to map a custom function that uses the stringr package over each string in the vector.

library(dplyr)
library(stringr)
library(purrr)

# custom function that accepts string input and counts the number 
# of non-alphanum characters
count_non_alnum <- function(x) {
  stringr::str_detect(x, "[^[:alnum:] ]") %>% sum()
}

# character vector of length 100K
vec <- rep("Hello. World.", 100000)  

# tokenize individual characters for each string
vec_tokens <- purrr::map(vec, function(x) {
  stringr::str_split(x, "") %>% unlist()
})

# count non-alphanum characters
purrr::map(vec_tokens, count_non_alnum)

# Time difference of 1.048214 mins



sessionInfo()
# R version 3.4.3 (2017-11-30)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 7 x64 (build 7601) Service Pack 1

My simulations consistently require about 1 minute to complete. I don't have much of a basis for expectation, but I am hoping there is a faster alternative. I am open to alternative R packages or interfaces (e.g. reticulate, Rcpp).

Upvotes: 2

Views: 193

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76470

The base R functions are much faster. Here is a sum/grepl solution and 4 different ways of calling the two functions.

library(microbenchmark)
library(ggplot2)
library(dplyr)
library(stringr)
library(purrr)

# custom function that accepts string input and counts the number 
# of non-alphanum characters
count_non_alnum <- function(x) {
  stringr::str_detect(x, "[^[:alnum:] ]") %>% sum()
}

count_non_alnum2 <- function(x) {
  sum(grepl("[^[:alnum:] ]", x))
}

# character vector of length 100K
vec <- rep("Hello. World.", 100)  

# tokenize individual characters for each string
vec_tokens <- purrr::map(vec, function(x) {
  stringr::str_split(x, "") %>% unlist()
})


# count non-alphanum characters
mb <- microbenchmark(
  Danny_purrr = purrr::map(vec_tokens, count_non_alnum),
  Rui_purrr = purrr::map(vec_tokens, count_non_alnum2),
  Danny_base = sapply(vec_tokens, count_non_alnum),
  Rui_base = sapply(vec_tokens, count_non_alnum2),
  unit = "relative"
)
mb
#Unit: relative
#        expr       min        lq      mean    median        uq       max neval cld
# Danny_purrr 58.508234 56.440147 52.854162 53.890724 53.464640 25.855456   100   c
#   Rui_purrr  1.026362  1.021998  1.011265  1.025648  1.025087  1.558001   100 a  
#  Danny_base 58.643098 56.398330 52.491478 53.857666 52.821759 27.981780   100  b 
#    Rui_base  1.000000  1.000000  1.000000  1.000000  1.000000  1.000000   100 a  


autoplot(mb)

enter image description here

Upvotes: 2

Related Questions