Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. flow = c(rep(NA,10),NAins(as.data.frame(runif(5000)), .1)$runif)
  2. rain = runif (length(flow))
  3. event = with(rle(!is.na(flow )),cbind(length=lengths[values],position=cumsum(c(1,lengths))[values]));
  4.  
  5. test_function = function(ndays, event, flow, rain,upboundary){
  6. flowvolume = rainvolume = raininweek = raininmonth =NULL;
  7. for (i in 1:(length(event)/2)){
  8. if (upboundary < event[,'position'][i]){
  9. flowvolume[i] = sum(flow[(event[,'position'][i]):(event[,'position'][i]+event[,'length'][i]-1)], na.rm = TRUE) # total flow during the non NA period
  10. rainvolume[i] = sum(rain[(event[,'position'][i]):(event[,'position'][i]+event[,'length'][i]-1)], na.rm = TRUE) # total rain during the non NA period
  11. raininweek[i] = sum(rain[(event[,'position'][i]-ndays[1]):(event[,'position'][i]-1)], na.rm = TRUE) #total rain imediate before NA with a constrained period of nday[1]
  12. raininmonth[i] = sum(rain[(event[,'position'][i]-ndays[2]-ndays[1]):(event[,'position'][i]-ndays[1]-1)], na.rm = TRUE) #total rain iprior to nday[1]
  13. } else {next}
  14. }
  15. -summary(lm(flowvolume ~ rainvolume + raininweek + raininmonth))$r.squared # to minimise R2
  16. }
  17.  
  18. results= optim(par=c(2,20), lower=c(1,10), upper=c(10,30),method="L-BFGS-B",test_function, event=event, rain=rain, flow=flow,upboundary=30)
  19.  
  20. ################################################################
  21. # RANDOMLY INSERT A CERTAIN PROPORTION OF NAs INTO A DATAFRAME #
  22. ################################################################
  23. NAins <- NAinsert <- function(df, prop){
  24. n <- nrow(df)
  25. m <- ncol(df)
  26. num.to.na <- ceiling(prop*n*m)
  27. id <- sample(0:(m*n-1), num.to.na, replace = FALSE)
  28. rows <- id %/% m + 1
  29. cols <- id %% m + 1
  30. sapply(seq(num.to.na), function(x){
  31. df[rows[x], cols[x]] <<- NA
  32. }
  33. )
  34. return(df)
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement