汇总表与一些列总结一个矢量与R中的变量

时间:2018-02-27 12:58:29

标签: r variables vector summary

我的桌子看起来像这样:

    df <- data.frame(week = c("one","one","two","two"),
                     Day = c("day1", "day2","day1","day2"),
                     daily_freq = c(100,110,90,90),
                     city1 = c(20,30,20,30),
                     city2 = c(10,20,30,40),
                     city3 = c(30,40,10,10),
                     city4 = c(40,20,30,10))

我正在计算几个汇总表,例如,一个表中包含该期间的总频率:

resume_table <- setDT(df)[, .( total_freq = sum(daily_freq),
                               city1 = sum(city1),
                               city2 = sum(city2),
                               city3 = sum(city3),
                               city4 = sum(city4))
                                       ,by = .(week)]

查找总频率如下所示的表格:

    week  total_freq city1 city2 city3 city4
    one        210    50    30    70    60
    two        180    50    70    20    40

但是因为我有几个城市(超过40个),而且我需要计算几个汇总表,所以我希望有一个带有城市的向量:

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

并且每次我对这个向量变量进行求和并且仍然对其他列求和时,能够调用此向量。 我的代码不起作用:

resume_table2 <- setDT(df)[, .(total_freq = sum(daily_freq),
                     lapply(.SD, sum), .SDcols = cities)
                               ,by = .(week)]

出了什么问题?

1 个答案:

答案 0 :(得分:0)

我们可以指定&#39;城市&#39;向量.SDcols中的向量并在.SD上方循环以获取sum

setDT(df)[, lapply(.SD, sum), .SDcols = cities]
#   city1 city2 city3 city4
#1:   105   100    55    65

如果我们需要&#39; daily_freq&#39;同时,再与“城市”联系起来

setDT(df)[, lapply(.SD, sum), .SDcols = c('daily_freq', cities)]
#    daily_freq city1 city2 city3 city4
#1:        325   105   100    55    65