mercredi 6 avril 2016

For loops and if statements r + preallocation

If the value is 1 in EA$phase then the equivalent location in a new vector OCC must be 90. So far I have this:

head(EA$phase)
[1] 1 1 1 1 2 2

OCC <- vector(mode = "list", length = 580) #Pre-allocate OCC
for(i in 1:length(EA$phase)) # For each element in EA$phase
{
  if (EA$phase[i]=="1"){OCC[i]=90} #If the value of EA$phase[1] is 1 then OCC[1]=90
  if (EA$phase[i]=="2"){OCC[i]=90}
  if (EA$phase[i]=="3"){OCC[i]=50}
  if (EA$phase[i]=="4"){OCC[i]=70}
  if (EA$phase[i]=="5"){OCC[i]=60}
  if (EA$phase[i]=="6"){OCC[i]=50}
  if (EA$phase[i]=="7"){OCC[i]=70}
  if (EA$phase[i]=="8"){OCC[i]=70}
  if (EA$phase[i]=="9"){OCC[i]=80}
  if (EA$phase[i]=="10"){OCC[i]=80}
}

But this isn't right somehow. Is there a way of making this more efficient/correct? Some trick?

Aucun commentaire:

Enregistrer un commentaire