For loops and if statements r + preallocation -


if value 1 in ea$phase equivalent location in new vector occ must 90. far 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)) # each element in ea$phase {   if (ea$phase[i]=="1"){occ[i]=90} #if value of ea$phase[1] 1 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 isn't right somehow. there way of making more efficient/correct? trick?

you can without for-loop (and without preallocation):

occ <- c(90, 90, 50, 70, 60,  50, 70, 70, 80, 80) occ <- occ[ea$phase] 

eventually want put result in dataframe:

ea$occ <- occ[ea$phase] 

the used technique indirect indexing: have variable (in case ea$phase), value index vector (in case occ).


Comments