7

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

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)

我已经用聚合函数尝试了很多东西,但不知道如何在没有观察到的情况下包含日期(零)。

4

3 回答 3

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)
于 2012-10-30T00:55:55.293 回答
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至关重要,它引入了NAs wheredf1df2不匹配而不是删除这些实例。

然后使用plyr包获取计数:

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

df2按 的唯一值分成组df2$date,然后找出有多少df2$var个 不是NA,然后返回该数字及其所代表的唯一值df2$date

于 2012-10-30T00:59:17.927 回答
0

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

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

于 2016-06-29T15:46:54.170 回答