我正在处理网球排名数据,并注意到有些日期没有数据。但是,我想填写上周的数据。
考虑数据结构
structure(list(date2 = structure(c(16076, 16076, 16076, 16076,
16076, 16076, 16076, 16076, 16076, 16076, 16083, 16083, 16083,
16083, 16083, 16083, 16083, 16083, 16083, 16083, 16090, 16097,
16097, 16097, 16097, 16097, 16097, 16097, 16097, 16097, 16097
), class = "Date"), rank = c(5L, 6L, 4L, 3L, 7L, 8L, 2L, 9L,
10L, 1L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, NA, 7L, 8L,
9L, 10L, 4L, 5L, 6L, 1L, 2L, 3L), Name = c("Del Potro,Juan Martin",
"Federer,Roger", "Murray,Andy", "Ferrer,David", "Berdych,Tomas",
"Wawrinka,Stanislas", "Djokovic,Novak", "Gasquet,Richard", "Tsonga,Jo-Wilfried",
"Nadal,Rafael", "Del Potro,Juan Martin", "Federer,Roger", "Berdych,Tomas",
"Wawrinka,Stanislas", "Gasquet,Richard", "Tsonga,Jo-Wilfried",
"Nadal,Rafael", "Djokovic,Novak", "Ferrer,David", "Murray,Andy",
NA, "Berdych,Tomas", "Federer,Roger", "Gasquet,Richard", "Tsonga,Jo-Wilfried",
"Del Potro,Juan Martin", "Ferrer,David", "Murray,Andy", "Nadal,Rafael",
"Djokovic,Novak", "Wawrinka,Stanislas"), points = c(5255L, 4355L,
5560L, 5800L, 4180L, 3890L, 12260L, 3140L, 3065L, 13130L, 5415L,
4355L, 4180L, 3890L, 3140L, 3065L, 13130L, 12260L, 5640L, 5560L,
NA, 4540L, 4355L, 3050L, 2885L, 5370L, 5280L, 4720L, 14330L,
10620L, 5710L)), .Names = c("date2", "rank", "Name", "points"
), class = "data.frame", row.names = c(722066L, 722067L, 722078L,
722106L, 722110L, 722111L, 722118L, 722139L, 722140L, 722143L,
722330L, 722331L, 722332L, 722333L, 722334L, 722335L, 722406L,
722407L, 722408L, 722409L, 722672L, 722677L, 722683L, 722684L,
722689L, 722748L, 722749L, 722750L, 723098L, 723099L, 723100L))
我用这种方法来填充,
nadates<-temp85[which(is.na(temp85$rank)),"date2"]
fillindates=as.Date(nadates)-7
nadatesfilled=temp85[temp85$date2 %in% fillindates,]
nadatesfilled$date2<-as.Date(nadatesfilled$date2)+7
temp85filled<-rbind(na.omit(temp85),nadatesfilled)
但是,我的问题是,有没有更好的方法?特别是,考虑到在某些情况下,我有2,3周后失踪(不在这个数据子集中)。我重复了这些代码以填补这些代码,但仍然有更好的方法吗?
答案 0 :(得分:2)
library("zoo")
temp85filled <- do.call(rbind,
lapply(na.omit(unique(temp85$rank)), function(rank) {
na.locf(temp85[(is.na(temp85$rank) | temp85$rank == rank),])
}))
比起先看起来有点棘手,因为有一行的日期应该被替换为与前一个日期相对应的整行行。为了解决这个问题,我分别针对每个级别进行了测试,但是对于每个级别,查看该级别或缺少级别(这就是为什么这不是简单的拆分 - 应用 - 组合问题)。在其中,na.locf
可用于填充缺失值(这确实假设数据按时间排序;如果不是,则可以在将其传递到na.locf
之前完成。 lapply
匿名函数)。 temp85fillled
未按日期排序,但可以是。 (temp85filled <- temp85filled[order(temp85filled$date2),]
)。