考虑以下因素
x = factor(c("1|1","1|0","1|1","1|1","0|0","1|1","0|1"))
我想计算此因素中字符“0”的出现次数。到目前为止,我发现的唯一解决方案是
sum(grepl("0",strsplit(paste(sapply(x, as.character), collapse=""), split="")[[1]]))
# [1] 4
对于这样一个简单的过程,此解决方案似乎非常复杂。有“更好”的选择吗? (由于该过程将在2000个元素长的因素上重复大约100,000次,因此我可能还会关心性能。)
最佳答案
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
或者
sum(nchar(gsub("[1 |]", '', x )))
# [1] 4
基于@Rich Scriven的评论
sum(nchar(gsub("[^0]", '', x )))
# [1] 4
基于@thelatemail的注释-使用
tabulate
的速度比上述解决方案快得多。这是比较。sum(nchar(gsub("[^0]", "", levels(x) )) * tabulate(x))
时间资料:
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
关于r - 计算此因子中 "0"的数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42545250/