所以说我有以下数据集:
keycard=c("a","b","c","b","c","b","c","a","b")
我想计算向量中“ bc”出现的次数。我该怎么办?
答案 0 :(得分:5)
您可以折叠keycard
向量并通过使用与grepRaw()
函数匹配的模式进行处理:
s <- paste(keycard, collapse = "")
length( grepRaw("bc", s, all = T) )
#[1] 3
答案 1 :(得分:1)
您可以执行以下类似的功能,其中vec
是向量,number
是您要查找的数字,beg
和end
的开始和结束您要查找的向量的位置:
sum_occurences <- function(vec, number, beg, end) {
accum <- Reduce(paste0, vec[beg:end], accumulate = T)
last_two <- substr(accum, nchar(accum) - 1, nchar(accum))
return(sum(last_two == as.character(number)))
}
您可以申请:
keycard = c(4,5,2,5,2,4,6,5,2)
sum_occurences(keycard, 52, 1, 5)
[1] 2