mardi 5 juin 2018

Counting couples in array with loop in r

I'm having some issues writing a simple for loop with conditions in r. I've got this array:

Temp <- c("A", "A", "B", "A", "C", "C", "A", "B")

I want to count the couples in this array, by using two indexes which are incremented during the loop.It's mandatory to follow the order of the sequence.

The final result for this array should be:

CountAA = 1
CountAB = 2
CountAC = 1
CountBA = 1
CountBB = 0
CountBC = 0
CountCA = 1
CountCB = 0
CountCC = 1

I've tried with this code, but it gives me an error

"Error in if (Temp[i] == "A" & Temp[j] == "A") { : 
  argument is of length zero"

Code

CountAA = 0
CountAB = 0
CountAC = 0
CountBA = 0
CountBB = 0
CountBC = 0
CountCA = 0
CountCB = 0
CountCC = 0
i = 1
j = 2

for (j in 1:length(Temp)-1){
    if (Temp[i]=="A" & Temp[j]=="A"){
      CountAA = CountAA + 1
      i = i + 1
      j = j + 1
    }
    if (Temp[i]=="A" & Temp[j]=="B"){
      CountAB = CountAB + 1
      i = i + 1 
      j = j + 1
    }
    if(Temp[i]=="A" & Temp[j]=="C"){
      CountAC = CountAC + 1
      i = i + 1
      j = j + 1
    }
    if(Temp[i]=="B" & Temp[j]=="A"){
      CountBA = CountBA + 1
      i = i + 1
      j = j + 1
    }
    if(Temp[i]=="B" & Temp[j]=="B"){
      CountBB = CountBB + 1
      i = i + 1
      j = j + 1
    }
    if(Temp[i]=="B" & Temp[j]=="C"){
      CountBC = CountBC + 1
      i = i + 1
      j = j + 1
    }
    if(Temp[i]=="C" & Temp[j]=="A"){
      CountCA = CountCA + 1
      i = i + 1
      j = j + 1
    }
    if(Temp[i]=="C" & Temp[j]=="B"){
      CountCB = CountCB + 1
      i = i + 1
      j = j + 1
    }
    if(Temp[i]=="C" & Temp[j]=="C"){
      CountCC = CountCC + 1
      i = i + 1
      j = j + 1
    }
}

Aucun commentaire:

Enregistrer un commentaire