从我的previous question,从数据集中,我如何使用它20分钟的时间间隔。
我尝试了两种解决方案,但两者都显示了相同的结果。当我尝试将其转换为不同的时间间隔(例如20分钟)时,我的数据集并未取得所有值。
是否可以将其转换为data.frame()而不是data.table()。这是akrun给出的答案之一:
x y date time
1 2 1-1-01 15:00
2 5 1-1-01 17:00
3 1 1-1-01 18:00
5 7 1-1-01 21:00
2 6 1-1-01 22:00
6 3 1-1-01 23:00
9 2 2-1-01 01:00
6 1 2-1-01 04:00
.....
library(data.table)
DT <- setDT(df1)[, {tmp <- as.numeric(substr(time,1,2))
list(time=sprintf('%02d:00', min(tmp):max(tmp)))}, date]
df1[DT, on=c('date', 'time')]
DT <- setDT(df1)[, list(time=sprintf('%02d:00', 0:23)) , date]
res <- df1[DT, on=c('date', 'time')
][,{tmp <- which(!(is.na(x) & is.na(y)))
.SD[tmp[1L]:tmp[length(tmp)]]}]
res
library(zoo)
res[, c('x', 'y') :=lapply(.SD, na.approx), .SDcols= x:y]
答案 0 :(得分:2)
请求运行以下代码...
df1 <- structure(list(x = c(1L, 2L, 3L, 5L, 2L, 6L, 9L, 6L), y = c(2L,
5L, 1L, 7L, 6L, 3L, 2L, 1L), date = c("1-1-01", "1-1-01", "1-1-01",
"1-1-01", "1-1-01", "1-1-01", "2-1-01", "2-1-01"), time = c("15:00",
"17:00", "18:00", "21:00", "22:00", "23:00", "01:00", "04:00"
)), .Names = c("x", "y", "date", "time"), class = "data.frame",
row.names = c(NA, -8L))
library(chron)
library(data.table)
time<-as.character(substr(times(00:71/72),1,5))
dates <- paste0(1:2,'-1-01')
all.dt <- expand.grid(date=dates,time=time)
big.data <- merge(all.dt, df1, all.x=TRUE)
现在,对于最后一部分,您可以通过运行以下代码来填写NA
library(zoo)
big.data <- within(big.data,{
x <- na.approx(x,na.rm=FALSE)
y <- na.approx(y,na.rm=FALSE)
})
答案 1 :(得分:0)
尝试使用xts。我使用某种不同的数据来“看到”结果:
indata <- read.table(text='x y date time
1 2 1-1-01 15:00
2 2 1-1-01 15:19
2 5 1-1-01 17:00
3 1 1-1-01 17:05
3 1 1-1-01 18:00
3 1 1-1-01 18:20
5 7 1-1-01 21:05
6 6 1-1-01 21:08
2 6 1-1-01 22:00
6 3 1-1-01 23:11
9 2 2-1-01 1:00
9 2 2-1-01 1:21
6 1 2-1-01 4:29
', header=TRUE,stringsAsFactors = F)
library(xts)
xt <- strptime(paste(indata$date,indata$time),
"%d-%m-%y %H:%M")
its=xts(x = indata[,1:2],
order.by = xt,
frequency = NULL)
period.apply(its, INDEX=endpoints(xt, on="minutes", k=20), FUN=mean)
x y
2001-01-01 15:19:00 1.5 2.0
2001-01-01 17:05:00 2.5 3.0
2001-01-01 18:00:00 3.0 1.0
2001-01-01 18:20:00 3.0 1.0
2001-01-01 21:08:00 5.5 6.5
2001-01-01 22:00:00 2.0 6.0
2001-01-01 23:11:00 6.0 3.0
2001-01-02 01:00:00 9.0 2.0
2001-01-02 01:21:00 9.0 2.0
2001-01-02 04:29:00 6.0 1.0