ordinal - How do I find the difference in levels between two vectors of ordered factors in R? -


let's have 2 ordered factors start , end same length , use same levels. how return vector shows me how many levels each element has changed start end?

so example let's have:

start = 'c5',  na,   'c3',   'c5',   't1' end =   'c5', 'c5',   na  ,  'c6',   'c6' levels: c2 < c3 < c4 < c5 < c6 < c7 < c8 < t1 < t2 < t3 < t4 < t5 < t6 < t7 < t8 < t9 < t10 < t11 < t12 < s1 < s2 < s3 < s45 

what ideally want simple end - start give me c(0, na, na, 1, -3)

here's code setting above example

lvls<-c("c2","c3","c4","c5","c6","c7","c8",         "t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12",         "s1","s2","s3","s45") start<-c('c5',  na,   'c3',   'c5',   't1')  start<-ordered(start,levels=lvls)  end<-c('c5', 'c5',   na  , 'c6',   'c6') end<-ordered(end,levels=lvls) 

found think unnecesarrily complicated way of doing it. i'll gladly accept simpler more elegant answer.

> start_lvls<-sapply(start,function(elem){match(true,c(elem==levels(elem)))}) > end_lvls<-sapply(end,function(elem){match(true,c(elem==levels(elem)))}) > end_lvls-start_lvls [1]  0 na na  1 -3 

and since have hundreds of ordered factors , because want able analyse difference between 2 of them use these make life easier:

# returns vector numeric value of level each ordered factor in orderedfactorvec numericlevels<-function(orderedfactorvec){   return(sapply(orderedfactorvec,function(elem){match(true,c(elem==levels(elem)))})) }  # returns vector numeric difference between 2 given ordered factor vectors (i.e end - start) levelschange<-function(start,end){  return(numericlevels(end)-numericlevels(start))  } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -