R中每天观察的数量

时间:2012-10-30 00:46:37

标签: r

我正在使用如下所示的数据框:

date<-c("2012-02-01", "2012-02-01", "2012-02-03", "2012-02-04", "2012-02-04", "2012-02-05", "2012-02-09", "2012-02-12", "2012-02-12")
var<-c("a","b","c","d","e","f","g","h","i")
df1<-data.frame(date,var)

我想创建第二个数据框,将每天观察的数量制成表格。在该数据帧中,未提及的日期将为零......导致类似这样的事情:

date<-c("2012-02-01","2012-02-02","2012-02-03","2012-02-04","2012-02-05","2012-02-06","2012-02-07","2012-02-08","2012-02-09","2012-02-10","2012-02-11","2012-02-12")
num<-c(2,0,1,2,1,0,0,0,1,0,0,2)
df2<-data.frame(date,num)

我已尝试使用聚合函数进行了许多操作,但无法弄清楚如何包含没有观察的日期(零)。

3 个答案:

答案 0 :(得分:2)

这是一种使用data.table

的方法
library(data.table)
DF1 <- as.data.table(df1)
# coerce date to a date object
DF1[, date := as.IDate(as.character(date), format = '%Y-%m-%d')]
# setkey for joining
setkey(DF1, date)

# create a data.table that matches with a data.table containing
# a sequence from the minimum date to the maximum date
# nomatch = NA includes those non-matching. 
# .N is the number of rows in the subset data.frame
# this is 0 when there are no matches 
DF2 <- DF1[J(DF1[,seq(min(date), max(date), by = 1)]), .N, nomatch = NA]
DF2

          date N
 1: 2012-02-01 2
 2: 2012-02-02 0
 3: 2012-02-03 1
 4: 2012-02-04 2
 5: 2012-02-05 1
 6: 2012-02-06 0
 7: 2012-02-07 0
 8: 2012-02-08 0
 9: 2012-02-09 1
10: 2012-02-10 0
11: 2012-02-11 0
12: 2012-02-12 2

使用reshape2::dcast

的方法

如果您确保date列的每一天都有您希望制表的级别

df1$date <- with(df1, factor(date, levels = as.character(seq(min(as.Date(as.character(date))), max(as.Date(as.character(date))), by = 1 ))))


df2 <- dcast(df1, date~., drop = FALSE)

答案 1 :(得分:0)

我最近处理过类似的事情。我会创建一个包含您要考虑的所有日期的数据框,并使用merge()函数来执行您的建议。

df1$date <- as.Date(df1$date, format = "%Y-%m-%d")
newdates <- data.frame(date=seq(as.Date('2012-02-01'),as.Date('2012-02-12'),1))
df2 <- merge(df1, newdates, by = "date", all = TRUE)

all = TRUE在这里至关重要,它引入了NA,其中df1df2不匹配,而不是删除这些实例。

然后使用plyr包来获取计数:

library(plyr)
ddply(df2, "date", function(x) sum(!is.na(x$var)))

这会按df2的唯一值将df2$date拆分为多个组,然后查找df2$var的值NA的多少个值,然后返回该数字以及唯一值它所代表的df2$date

答案 2 :(得分:0)

将索引转换为Postxct格式,然后:

counts <- data.frame(table(as.Date(index(my_data_frame))))