2017-07-26 81 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