2014-12-10 2 views
3

임에 처음 뵙겠습니다. 내 첫 번째 어려움이 있습니다. 나는 ca.10000 obs의 데이터 세트를 가지고있다. 365 일 동안 나는 사건의 발생을 포착한다. 이 사건은 매월 처음 14 일 동안 만 표시됩니다. 나는 해당 월의 이전 사건을 평균하여 (시간 기준으로) 추가 16 일을 보충하고 싶다. 시간별 평균 시간을 계산하는 방법은 무엇입니까?

    day   hours  occurrence 
        2000-01-01  1   5 
        2000-01-01  2   6 
        2000-01-01  3   7 
        ...   ...  ... 
        2000-01-01  23   3 
        2000-01-01  24   2 
        ...   ...  ... 
        2000-01-02  1   4 
        2000-01-02  2   2 
        2000-01-02  3   5 
        ...   ...  ... 
        2000-01-02  23   2 
        2000-01-02  24   1 
        ... 
        ... 
        2000-01-15  1   average of the previous 1 hours((5+4+n)/2*k)) 
        2000-01-15  2   average of the previous 2 hours ((6+2+n)/2*k)) 
        2000-01-15  3   average of the previous 3 hours((7+5+n)/2*k)) 
        ...   ...   ... 
        2000-01-15  23   average of the previous 23 hours 
        2000-01-15  24   average of the previous 24 hours 
        ...   ...   ... 
        ...   ...   ... 
        2000-01-30 
        2000-01-30 
        2000-01-30 
        2000-01-30 
        ...   ...   ... 
        ...   ...   ... 
        2000-02-01 
        2000-02-01 
        2000-02-01 
        2000-02-01 
        ...   ...   ... 
        ... 
        ...   ...   ... 
        2000-12-24 

내가

   aggregate(occurences ~ hours, mean) 

을 시도했지만 결과는 무의미했고, 내가 상상으로 나는

   tapply(X = occurences, INDEX = list(hours), FUN = Mean) 

불행하게도 모두 didnt 한 일을하려고 다음과 같이

구조입니다. 나는 해당 달을 함수에 포함시키는 것이 필요하다고 생각한다. 그러나 나의 수단은 제한된 것으로 보인다.

답변

4

시도해 볼 수 있습니다. 예제를 더 작게 만들기 위해 매월 1-4 일과 매월 0-1 시간의 데이터 만 선택합니다. 각 1 일에 & 2에 데이터가 발생하고 2 일째에 & 3 데이터가 누락되었습니다. @Henrik보다

library(dplyr) 

# create dummy data 
set.seed(123) # for reproducibility of sample 

d1 <- data.frame(time = seq(from = as.POSIXct("2000-01-01"), 
          to = as.POSIXct("2000-02-28"), 
          by = "hour")) 
d1 <- d1 %>% 
    mutate(hour = as.integer(format(time, "%H")), 
     day = as.integer(format(time, "%d")), # <~~ only needed to generate sample data 
     month = as.integer(format(time, "%m")), 
     occurence = sample(1:10, length(time), replace = TRUE), 
     occurence = ifelse(day %in% 1:2, occurence, NA)) %>% # <~~~ data only for day 1-2 
    filter(hour %in% 0:1 & day %in% 1:4) %>% # <~~~ smaller example: select hour 0-1, day 1-4 
    select(-day) 

# calculate mean occurrence per month and hour 
d2 <- d1 %>% 
    group_by(month, hour) %>% 
    summarise(mean_occ = round(mean(occurence, na.rm = TRUE), 1)) 
d2 
# month hour mean_occ 
# 1  1 0  5.0 
# 2  1 1  8.0 
# 3  2 0  5.5 
# 4  2 1  6.5 


# replace missing occurrence with mean_occ 
d3 <- d1 %>% 
    left_join(d2, by = c("hour", "month")) %>% 
    mutate(occurence2 = ifelse(is.na(occurence), mean_occ, occurence)) %>% 
    select(-month, -mean_occ) 

d3 
# hour    time occurence occurence2 
# 1  0 2000-01-01 00:00:00   3  3.0 
# 2  1 2000-01-01 01:00:00   8  8.0 
# 3  0 2000-01-02 00:00:00   7  7.0 
# 4  1 2000-01-02 01:00:00   8  8.0 
# 5  0 2000-01-03 00:00:00  NA  5.0 
# 6  1 2000-01-03 01:00:00  NA  8.0 
# 7  0 2000-01-04 00:00:00  NA  5.0 
# 8  1 2000-01-04 01:00:00  NA  8.0 
# 9  0 2000-02-01 00:00:00   4  4.0 
# 10 1 2000-02-01 01:00:00   6  6.0 
# 11 0 2000-02-02 00:00:00   7  7.0 
# 12 1 2000-02-02 01:00:00   7  7.0 
# 13 0 2000-02-03 00:00:00  NA  5.5 
# 14 1 2000-02-03 01:00:00  NA  6.5 
# 15 0 2000-02-04 00:00:00  NA  5.5 
# 16 1 2000-02-04 01:00:00  NA  6.5 
+0

정교하게 답변 해 주셔서 감사합니다. 한 달에 여러 가지 길이 (28-30-31)에 대해 해당 조정을 조정할 수 있습니까? – Googme

+0

그게 사실이야. 미안하다. R Newbie와 STATA 활동가에게 그러한 fuctions는 드문 경우이므로 진화 할 시간이 필요합니다. – Googme

1

약간 다른 접근 방식 :

library(lubridate) 
library(data.table) 
## 
setDT(Df) 
Df[,month:=month(days)] 
Df[,year:=year(days)] 
## 
naDf <- Df[mday(days)>14,] 
subDf <- Df[mday(days)<=14,] 
## 
avgDf <- subDf[ 
    , 
    list(occurrence=mean(occurrence)), 
    by="month,year"] 
## 
naDf <- base::merge(
    x=naDf[,list(days,hours,month,year)], 
    y=avgDf, 
    by=c("month","year")) 
newDf <- rbind(
    subDf,naDf, 
    use.names=TRUE)[order(days,hours),] 

데이터 : 난 단지 데이터의 년을 사용하지만,이 집계 이후 긴 시간 창에 대해 잘 작동해야하고 있습니다 조인 년 및 월 기준으로 수행됩니다. 너무 플롯이되지 않은 :

Df[mday(days)>14, 
    occurrence:=NA] 
Df[,datetime:=as.POSIXct(
    days,tz="GMT")+3600*(4+hours)] 
## 
newDf[,datetime:=as.POSIXct(
    days,tz="GMT")+3600*(4+hours)] 
## 
library(ggplot2) 
ggplot(
    data=newDf[200:800,], 
    aes(x=datetime,y=occurrence))+ 
    geom_line(color="red") 
ggplot(
    data=Df[200:800,], 
    aes(x=datetime,y=occurrence))+ 
    geom_line() 

enter image description here

내가 행의 하위 집합 (800 200)를 사용

enter image description here

:

d0 <- as.Date("2000-01-01") 
set.seed(123) 
## 
Df <- data.frame(
    days=rep(d0+0:364,each=24), 
    hours=rep(1:24,365), 
    occurrence=sample(1:15,24*365,replace=TRUE)) 

단지 전성 검사로

너무 혼잡했다.

+1

시간과 노력에 감사드립니다 ... – Googme

관련 문제