将数据集聚合为“忽略”分类变量

时间:2016-04-24 11:45:44

标签: r dataset aggregation categorical-data

我有这样的数据集,结构如下

Neighborhood,  var1,   var2,   COUNTRY, DAY, categ 1, categ 2
     1          700     724      AL      0      YES    YES
     1          500     200      FR      0      YES     NO
    ....
     1          701     659      IT      1      NO      YES
     1          791     669      IT      1      NO      YES
    ....
     2          239     222      GE      0      YES      NO

依旧......

因此,层次结构是“邻居> DAY> COUNTRY”,对于每个社区,每天,对于每个国家,我都会观察到var1,var2,categ1和categ2

我对分析这个国家的时刻不感兴趣,所以我想要做的是汇总(通过对“国家”字段var1和var2进行“总结”,分类变量Categ1和categ2不受其影响国家),并有一个数据集,每个社区和每一天给我一个关于var1,var2,categ1和categ2的信息

我对R编程很陌生,基本上不知道很多软件包(我会用c ++编写一个程序,但我强迫自己学习R)... 所以你对如何做到这一点有任何想法吗?

数据

df1 <- structure(list(Neighborhood = c(1L, 1L, 1L, 1L, 2L),
                      var1 = c(700L, 500L, 701L, 791L, 239L),
                      var2 = c(724L, 200L, 659L, 669L, 222L),
                      COUNTRY = c("AL", "FR", "IT", "IT", "GE"),
                      DAY = c(0L, 0L, 1L, 1L, 0L),
                      `categ 1` = c("YES", "YES", "NO", "NO", "YES"), 
                      `categ 2` = c("YES", "NO", "YES", "YES", "NO")),
                 .Names = c("Neighborhood", "var1", "var2", "COUNTRY", "DAY", "categ 1", "categ 2"),
                 class = "data.frame", row.names = c(NA, -5L))
编辑:@akrun

当我尝试你的命令时,结果是:

聚合(.~邻居+ DAY + COUNTRY,data = df1 [!grepl(“^ categ”,姓名(df1))],意思是

     Neighborhood, DAY, COUNTRY, var1, var2

1            1      0      AL     700  724
2            1      0      FR     500  200
3            2      0      GE     239  222
4            1      1      IT     746  664

但是(在这个例子中)我想要的是:

         Neighborhood, DAY,  var1, var2

1            1          0     1200  924           //wher var1=700+500....
2            1          1     1492  1328
3            2          0     239  222

1 个答案:

答案 0 :(得分:1)

如果我们对“分类”列不感兴趣,我们可以grep将它们用于aggregate

aggregate(.~Neighborhood+DAY, data= df1[!grepl("^(categ|COUNTRY)", names(df1))], sum)
#   Neighborhood DAY var1 var2
#1            1   0 1200  924
#2            2   0  239  222
#3            1   1 1492 1328

或使用dplyr

library(dplyr)
df1 %>%
   group_by(Neighborhood, DAY) %>%
   summarise_each(funs(sum), matches("^var"))
#  Neighborhood   DAY  var1  var2
#         (int) (int) (int) (int)
#1            1     0  1200   924
#2            1     1  1492  1328
#3            2     0   239   222