提问人:Hack-R 提问时间:11/8/2014 更新时间:11/8/2014 访问量:89
将 R 中缺少的每周数据点填写为每个 ID 的 0
Fill in Missing Weekly Data Points in R as 0 for Each ID
问:
我有这种形状的数据:
> head(posts)
id week_number num_posts
1 UKL1.1 1 4
2 UKL1.1 6 9
3 UKL1.2 1 2
4 UKL1.3 1 8
5 UKL1.3 2 7
6 UKL1.3 3 3
我想使每个 (1,2,3,4,5,6) 都有一行,如果数据中还没有,那么应该 = 0id
week_number
week_number
posts
我已经看到使用具有真实时间序列数据的包完成了此操作,但是在没有创建适当的版本或使用该包的情况下,有没有办法直接执行此操作?zoo
POSIXct
Date
week_number
答:
1赞
jlhoward
11/8/2014
#1
这是使用 .data.table
library(data.table)
setDT(posts) # convert posts to a data.table
all.wks <- posts[,list(week_number=min(week_number):max(week_number)),by=id]
setkey(posts,id,week_number) # index on id and week number
setkey(all.wks,id,week_number) # index on id and week number
result <- posts[all.wks] # data.table join is very fast
result[is.na(num_posts),num_posts:=0] # convert NA to 0
result
# id week_number num_posts
# 1: UKL1.1 1 4
# 2: UKL1.1 2 0
# 3: UKL1.1 3 0
# 4: UKL1.1 4 0
# 5: UKL1.1 5 0
# 6: UKL1.1 6 9
# 7: UKL1.2 1 2
# 8: UKL1.3 1 8
# 9: UKL1.3 2 7
# 10: UKL1.3 3 3
另一种方式:
my_fun <- function(x) {
weeks = with(x, min(week_number):max(week_number))
posts = with(x, num_posts[match(weeks, week_number)])
list(week_number=weeks, num_posts=posts)
}
setDT(posts)[, my_fun(.SD), by=id]
.SD
指数据子集;它包含与 中指定的每个组对应的数据子集,除分组列 = 之外的所有列。by
id
然后,您可以如上所示替换 s。NA
评论