测试变量向量并对表进行求和,在R

时间:2018-02-27 16:03:16

标签: r vector summary

我有一张这样的表:

df <- read.table(text = 
                "  Day      city    gender     week
                 'day1'    'city1'   'M'       'one'
                 'day2'    'city2'   'M'       'two'
                 'day1'    'city3'   'F'       'two'
                 'day2'    'city4'   'F'       'two'", 
                 header = TRUE, stringsAsFactors = FALSE) 

我计算这样的汇总表:

daily_table <- setDT(df)[, .(Daily_Freq = .N,
                             men = sum(gender == 'M'),
                             women = sum(gender == 'F'),
                             city1 = sum(city == 'city1'),
                             city2 = sum(city == 'city2'),
                             city3 = sum(city == 'city3'),
                             city4 = sum(city == 'city4'),
                             city5 = sum(city == 'city5'))
                         , by = .(week,Day)]

制作此表:

   week  Day Daily_Freq men women city1 city2 city3 city4 city5
    one day1          1   1     0     1     0     0     0     0
    two day2          2   1     1     0     1     0     1     0
    two day1          1   0     1     0     0     1     0     0

但是因为我有几个城市,所以我想使用带有名字的矢量:

cities <- c("city1","city2","city3","city4","city5")

请注意,我的向量中有5个城市,即使其中一个城市的出现次数为零,我希望它出现在我的最终表格中。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

为了确保R显示city5,即使没有对该值的观察,请将其添加为因子级别:

setDT(df)

df[, city :=  factor(city,
                     levels = c("city1","city2","city3","city4","city5"))]

为了避免为city的每个级别编写测试,您可以迭代city级别,如下所示:

daily_table <- df[, c(.(Daily_Freq = .N,
                        men = sum(gender == 'M'),
                        women = sum(gender == 'F')),
                      lapply(setNames(levels(city), levels(city)),
                             function(x) sum(city == x))),
                  by = .(week,Day)]
daily_table
##    week  Day Daily_Freq men women city1 city2 city3 city4 city5
## 1:  one day1          1   1     0     1     0     0     0     0
## 2:  two day2          2   1     1     0     1     0     1     0
## 3:  two day1          1   0     1     0     0     1     0     0