samedi 16 février 2019

In R, For-loop or command for counting number of times a pattern of numbers shows up in a dataset

So let's say I have the following dataset: keycard=c(4,5,2,5,2,4,6,5,2)

I want to count the number of times the number pattern "52" comes up in the dataset. I tried the following for-loop; basically I'm trying to say that for every integer, if it equals 5 and the next integer in the series equals 2, then increase the count by 1:

keycount <- 0
for (i in 1:length(keycard)){
if (i == 5 & i + 1 == 2) keycount = keycount + 1}
print (keycount)

But this doesn't seem to work for me. Could you please help me determine how to fix my for-loop or come up with a better, faster way for counting "52"? Sorry I'm a beginner at programming so I apologize if my formatting isn't very good. Thank you.

Aucun commentaire:

Enregistrer un commentaire