2017-03-08 85 views
1

多個級別3路表我想打開以下,手動輸入的表,輸入作爲在R A data.frame,代碼here以下:車削一個data.frame與R中

tab <- data.frame(expand.grid(
    Hair = c("Black", "Brown", "Red", "Blond"), 
    Eye = c("Brown", "Blue", "Hazel", "Green"), 
    Sex = c("Male", "Female")), 
    count = c(32,53,10,3,11,50,10,30,10,25,7,5,3,15,7,8, 
      36,66,16,4,9,34,7,64,5,29,7,5,2,14,7,8)) 

tab 

    Hair Eye Sex count 
1 Black Brown Male 32 
2 Brown Brown Male 53 
3 Red Brown Male 10 
4 Blond Brown Male  3 
... 

到一個表作爲原始HairEyeColor {datasets}三維陣列中:

HairEyeColor 
, , Sex = Male 

     Eye 
Hair Brown Blue Hazel Green 
    Black 32 11 10  3 
    Brown 53 50 25 15 
    Red  10 10  7  7 
    Blond  3 30  5  8 

, , Sex = Female 

     Eye 
Hair Brown Blue Hazel Green 
    Black 36 9  5  2 
    Brown 66 34 29 14 
    Red  16 7  7  7 
    Blond  4 64  5  8 

我試圖xtabsftable和沒有成功。

+1

'XTABS(計數〜,數據=標籤)'是不是? – thelatemail

+0

@thelatemail相當簡潔,但有效。發佈它作爲答案的一些觀點... – Toni

回答

3

由於每個值是一個獨特的類別,你可以做:

xtabs(count ~ ., data=tab) 
1

如果你想你的結果是data.frames的名單,與tidyverse包貼:

library(tidyverse) 
tab %>% 
    split(.$Sex) %>% 
    purrr::map(tidyr::spread, Eye, count) 
#> $Male 
#> Hair Sex Brown Blue Hazel Green 
#> 1 Black Male 32 11 10  3 
#> 2 Brown Male 53 50 25 15 
#> 3 Red Male 10 10  7  7 
#> 4 Blond Male  3 30  5  8 
#> 
#> $Female 
#> Hair Sex Brown Blue Hazel Green 
#> 1 Black Female 36 9  5  2 
#> 2 Brown Female 66 34 29 14 
#> 3 Red Female 16 7  7  7 
#> 4 Blond Female  4 64  5  8 
0

一個base R選項tapply

tapply(tab[,'count'], tab[1:3], FUN = I) 

或者我們可以使用dcast

library(data.table) 
setDT(tab)[, list(list(dcast(.SD, Hair ~Eye))), Sex]$V1 

或者,它可能是更好的有一個二維數據

dcast(setDT(tab), Hair + Sex ~Eye)