r - How do I increase or decrease an ordered factor's level? (Make a factor equal to the very next level) -
i have 2 lists of ordered factors , b, both contain thousands of items , have same ordinal scale of 30 levels. want find out how many items in equal or within 1 level above or below item @ same location in b
if scale numeric convert ordered factors numeric values , following:
table(a==b || a==(b+1) || a==(b-1))
however, of course, '+' not meaningful factors. do? write giant nested if statement or change ordinal scale numbers according level can convert ordered factors numeric... these seem roundabout (and lengthy) solutions i'd assume easy: how increase or decrease ordered factor's level?
if have
x<-ordered("b",levels=c("a","b","c"))
how make x[1]
equal "c"
incrementing current level?
sidenote: of course, in first example above i'd need account factors on lower , upper end of scale, think (hope) easy enough figure out once question has been answered.
you should able modify example output want
set.seed(7) df <- data.frame(a=sample(paste('a',seq(1:5),sep=''),5000,replace=true), b=sample(paste('a',seq(1:5),sep=''),5000,replace=true)) table(df$a) table(df$b) fa=factor(levels(df$a)) ia=0 (a in fa) { ia=ia+1 cat('for factor',a,'\n') na = sum(df$a==a) nb = sum(df$b==a) cat(' df$a has',na,'\n') cat(' df$b has',nb,'\n') nbm1 = -1 if (ia>1) { am1 <- fa[ia-1] nbm1 = sum(df$b==am1) cat(' df$b has',as.character(am1),', ',nbm1,'\n') } nbp1 = -1 if (ia<length(fa)) { ap1 <- fa[ia+1] nbp1 = sum(df$b==ap1) cat(' df$b has',as.character(ap1),', ',nbp1,'\n') } if (na == nbm1) { cat(' df$a[a] has same number df$b[a-1]\n') } else { cat(' df$a[a] not have same number df$b[a-1]\n') } if (na == nbp1) { cat(' df$a[a] has same number df$b[a+1]\n') } else { cat(' df$a[a] not have same number df$b[a+1]\n') } }
Comments
Post a Comment