Help on a simple Monte-Carlo Significance test (probability of occurrence) I would like to perform a statistical significance based on Monte Carlo simulation in R but I don't know how to formulate this correctly.
I have the following data set:
[Link to data]
(https://www.dropbox.com/s/29zgm8nm39qyh7m/data_rainfall.csv?dl=0)
There are four columns (Year, Month, Day, Phase, and Rainfall).
[Problem]
I want to know the likelihood of occurrence (significance) of getting
(a) rainfall below 5 mm/day for at least 3 consecutive days AND whose first day is in phase 1 (in each year).
[Here's what I have so far]
dat<-read.csv("data_rainfall.csv",header=T)
dat2<-as.data.frame(cbind(dat$phase,dat$Rainfall))

The significance function:
sig.test <- function (){
s1 <- dat2[sample(1:nrow(dat2),5,replace=T),]
  res<-sum(rle((s1$V1<5))$lengths >=3 & rle((s1$V2==1))$lengths >=3 )
return(sum(res)>0)
}

runs <- 1000
sig <- sum(replicate(runs,sig.test()))/runs

The result is always 1 which is odd.  I think there is a problem with how I calculate. the p value.
How can I do this correctly in R? 
I'll appreciate any help on this. 
--Lyndz
 A: You need a function to get at least 3 consecutive days less than 5 and first day is phase 1, using rle is ok, you need to get back the index:
dat2<-dat[,c("phase","Rainfall")]
RLE = rle(dat2$Rainfall<5)

Run Length Encoding
  lengths: int [1:728] 11 2 2 5 1 2 3 7 13 1 ...
  values : logi [1:728] TRUE FALSE TRUE FALSE TRUE FALSE ...

start_idx = cumsum(c(1,RLE$lengths[-length(RLE$lengths)]))
head(start_idx)
[1]  1 12 14 16 21 22

And we use this to get back whether the first entry is a phase 3:
phase_at_start = dat2$phase[start_idx]

Then it's a matter of combining the booleans, and wrapping it into a function:
countruns = function(x){
RLE = rle(x$Rainfall<5)
start_idx = cumsum(c(1,RLE$lengths[-length(RLE$lengths)]))
phase_at_start = x$phase[start_idx]
sum(RLE$lengths>=3 & phase_at_start==3)
}

My suggestion is to permute the rainfall column, so that you preserve the structure and occurrence of phase in the first column. I suppose what you are interested in is whether it's by chance you see 3 consecutive days of low rainfall If this works you can go on and experiment with the other columns:
sim.test <- function (x){
x$Rainfall <- sample(x$Rainfall)
countruns(x)
}

runs <- 1000
sim <- replicate(runs,sig.test(dat))
hist(sim,br=100)


