R-跨数据表列的计数/数据操作

时间:2018-12-18 17:28:34

标签: r data.table

我在数据表中的下面三列: 特拉华

年份是分类列。

+----+------+--------+
| No | Year | County |
+----+------+--------+
|  1 | 2011 | CHAVES |
|  2 | 2010 | CHAVES |
|  3 | 2010 | CHAVES |
|  4 | 2010 | CHAVES |
|  5 | 2010 | CHAVES |
|  6 | 2010 | CHAVES |
|  7 | 2010 | CHAVES |
|  8 | 2008 | CHAVES |
|  9 | 2008 | CHAVES |
| 10 | 2010 | CHAVES |
| 11 | 2010 | CHAVES |
| 12 | 2011 | CHAVES |
| 13 | 2011 | CHAVES |
| 14 | 2010 | CHAVES |
| 15 | 2006 | EDDY   |
| 16 | 2007 | EDDY   |
| 17 | 2008 | EDDY   |
| 18 | 2011 | EDDY   |
| 19 | 2013 | EDDY   |
| 20 | 2005 | EDDY   |
| 21 | 2010 | EDDY   |
| 22 | 2001 | EDDY   |
| 23 | 2001 | EDDY   |
| 24 | 2010 | EDDY   |
| 25 | 2009 | EDDY   |
+----+------+--------+

我可以通过使用“ table”来获得每个分类列的表格结果:

> table(Delaware$Year)

2001 2005 2006 2007 2008 2009 2010 2011 2013 
   2    1    1    1    3    1   11    4    1 
> table(Delaware$County)

CHAVES   EDDY 
    14     11 

但是我想获得以下信息:

请给我每个“县”的数量; Chaves或Eddy 为:

2006年有多少人

2007年有多少人

2008年有多少人

2009年有多少..

dput格式的数据。

有关发布的数据格式,请参见What can R do about a messy data format?

Delaware <-
structure(list(No = 1:25, Year = structure(c(8L, 7L, 
7L, 7L, 7L, 7L, 7L, 5L, 5L, 7L, 7L, 8L, 8L, 7L, 3L, 
4L, 5L, 8L, 9L, 2L, 7L, 1L, 1L, 7L, 6L), 
.Label = c("2001", "2005", "2006", "2007", 
"2008", "2009", "2010", "2011", "2013"), 
class = "factor"), County = structure(c(1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = 
c("CHAVES", "EDDY"), class = "factor")), 
row.names = c(NA, -25L), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

为什么不呢?

table(Delaware$Year, Delaware$County)