【问题标题】:In R, subset data using longest contiguous stretch of non-NA values在 R 中,使用非 NA 值的最长连续延伸的子集数据
【发布时间】:2020-08-19 15:53:01
【问题描述】:

我正在为线性回归准备数据,并希望通过使用给定年份和站点中最长的连续非 NA 值来解决缺失值 (NA)。

我尝试过 na.contiguous() 但我的代码没有按年份或站点应用该函数

感谢您的帮助

测试数据是跨 2 年和 2 个地点的多变量时间序列。我希望该解决方案能够容纳更多年和 32 个站点的数据——因此一定程度的自动化和 qa/qc 值得赞赏。


    library(dataRetrieval)
    library(dplyr)

    # read in Data, q is  discharge and wt is stream temperature
    wt<-readNWISdv(siteNumbers=c("08181800","07308500"),
    parameterCd=c("00010","00060"), statCd=c("00003"), 
    startDate="1998-07-01", endDate="1999-09-30" )
    dfwt<-wt%>%
      group_by(site_no)%>%
      select(Date,site_no,X_00010_00003,X_00060_00003)%>%
      rename(wt=X_00010_00003,q=X_00060_00003)

    #Subset summer season, add dummy air temp (at).

    dfwt$Date<-ymd(dfwt$Date, tz=Sys.timezone())
    dfwt$month<-month(dfwt$Date)
    dfwt$year<-year(dfwt$Date)
    df<- dfwt %>%
      group_by(site_no)%>%
      subset(month>=7 & month<=9)%>%
      mutate(at=wt*1.3) 
    # add NA
    df[35:38,3]<-NA
    df[155,3]<-NA
    df[194,3]<-NA

    test<-df%>%
      group_by(site_no, year)%>%
      na.contiguous(df) 

【问题讨论】:

    标签: r time-series linear-regression na contiguous


    【解决方案1】:

    使用 for 循环我找到了以下解决方案,

    library(zoo)
    library(plyr)
    library(lubridate)
    zoo(df)
    
    sites<-as.vector(unique(df$site_no))
    
    bfi_allsites<-data.frame()
    
    for(i in 1:2){
      
      site1<-subset(dfz, site_no==sites[i])
      str(site1)
      
      ss1<-split(site1,site1$year)
      site1result<-lapply(ss1,na.contiguous)#works
      site_df <- ldply(site1result,data.frame)
      bfi_allsites<-rbind(bfi_allsites, site_df)
    }
    head(bfi_allsites)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多