1

我想打开以下手动输入的表格,在 R 中作为 data.frame 输入,遵循此处的代码:

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没有成功。

4

3 回答 3

3

由于每个值都属于一个独特的类别,您可以这样做:

xtabs(count ~ ., data=tab)
于 2017-03-08T01:47:09.267 回答
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
于 2017-03-08T02:04:56.727 回答
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)
于 2017-03-08T03:13:36.697 回答