更新时间:2022-03-08 22:49:21
如@DWin所述,table()
不是用于求和,而是用于记录计数.
As @DWin states, table()
is not for summation, but for record counts.
我给出了使用plyr
,data.table
和aggregate
all_data <- expand.grid(country = paste('Country', LETTERS[1:3]),
date = seq(as.Date('2012/01/01'), as.Date('2012/12/31'), by = 1) )
all_data[['ed_visits']] <- rpois(nrow(all_data), lambda = 5)
# using plyr
library(plyr)
by_date_plyr <- ddply(all_data, .(date), summarize, visits = sum(ed_visits))
# using data.table
library(data.table)
all_DT <- data.table(all_data)
by_date_dt <- all_DT[, list(visits = sum(ed_visits)), by = 'date' ]
# using aggregate
by_date_base <- aggregate(ed_visits ~ date, data = all_data, sum)