2017-07-26 80 views
0

联表我要重新排序我希望能够订购的因素0和1。我想要的结果的cont.table排序不改变表类

test.a <- c(rep(1,20),rep(0,40)) 
test.b <- c(rep(1,25),rep(0,35)) 

cont.table <- addmargins(table(test.a, test.b)) 

    test.b 
test.a 0 1 Sum 
    0 35 5 40 
    1 0 20 20 
    Sum 35 25 60 

因素是这个

 1 0 Sum 
1 20 0 20 
0 5 35 40 
Sum 25 35 60 

我做到了这样,但我失去了类表,这是需要我

> tbl <- as.data.frame.matrix(addmargins(table(test.a, test.b))) 
> tbl2 <- cbind(tbl[2],tbl[1],tbl[3]) 
> tblfinal <- rbind(tbl2[2,],tbl2[1,],tbl2[3,]) 

> as.table(tblfinal) 
Error in as.table.default(tblfinal) : cannot coerce to a table 

有没有可能呢?越简单越好

+0

非常有用!我会接受你的回答,但它是一个评论! –

回答

3

让您test.x对象因子与定义的顺序,那么表等将适当分类。例如:

test.a <- factor(test.a,levels=c(1,0)) 
test.b <- factor(test.b,levels=c(1,0)) 
addmargins(table(test.a,test.b)) 

#  test.b 
#test.a 1 0 Sum 
# 1 20 0 20 
# 0 5 35 40 
# Sum 25 35 60 
+0

如果,而不是一堆0和1,我有“+”和“ - ”,当因素(,水平=“+”,“ - ”)它没有给我什么 –

+1

@JoseVictorZambrana - 那是因为你的代码是错误的。 'factor(x,levels = c(“+”,“ - ”))'会工作得很好。 – thelatemail

1

您可以通过COL /行名称只是重新排序:

cust_name <- c('1', '0', 'Sum') 
cont.table[cust_name, cust_name] 

     test.b 
test.a 1 0 Sum 
    1 20 0 20 
    0 5 35 40 
    Sum 25 35 60