x = factor(c("1|1","1|0","1|1","1|1","0|0","1|1","0|1")) x # [1] 1|1 1|0 1|1 1|1 0|0 1|1 0|1 # Levels: 0|0 0|1 1|0 1|1 sum( unlist( lapply( strsplit(as.character(x), "|"), function( x ) length(grep( '0', x ))) ) ) # [1] 4
or
sum(nchar(gsub("[1 |]", '', x )))
Based on comments by @Rich Scriven
sum(nchar(gsub("[^0]", '', x )))
Based on @thelatemail comment - using tabulate is much faster than the above solution. Here is a comparison.
sum(nchar(gsub("[^0]", "", levels(x) )) * tabulate(x))
Time Profile:
x2 <- sample(x,1e7,replace=TRUE) system.time(sum(nchar(gsub("[^0]", '', x2 )))); # user system elapsed # 14.24 0.22 14.65 system.time(sum(nchar(gsub("[^0]", "", levels(x2) )) * tabulate(x2))); # user system elapsed # 0.04 0.00 0.04 system.time(sum(str_count(x2, fixed("0")))) # user system elapsed # 1.02 0.13 1.25
source share