Last active
June 21, 2017 19:56
-
-
Save hillar/6659934 to your computer and use it in GitHub Desktop.
counting 'waves' or 'ticks' ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
has_waves <- function(c,try2=FALSE,try3=FALSE){ | |
lc <- length(c)-1 | |
if (lc < 3) { | |
return(NA) | |
} | |
notnas <- diff(which(!is.na(c))) | |
notnas <- notnas[notnas>1] | |
lnotnas <- length(notnas) | |
lunotnas <- length(unique(notnas)) | |
if (lunotnas==1 & 2 < lnotnas & lnotnas < lc){ | |
return (lnotnas) # spaces between are all equal length | |
} | |
else { | |
nas <- diff(which(is.na(c))) | |
nas <- nas[nas>1] | |
lnas<-length(nas) | |
lunas<-length(unique(nas)) | |
if (lunas ==1 & 2 < lnas & lnas < lc){ | |
return (lnas) # value groups are all equal length | |
} | |
else { | |
require('e1071') # dep on kurtosis | |
knas <- kurtosis(nas) | |
if (!is.na(knas)){ | |
knotnas <- kurtosis(notnas) | |
if (!is.na(knotnas)){ | |
if (knotnas > knas) { # choose 'better' return value | |
return (knotnas/lnotnas) | |
} | |
else { | |
return (knas/lnas) | |
} | |
} | |
else{ | |
return (knas/lnas) | |
} | |
} | |
else{ | |
knotnas <- kurtosis(notnas) | |
if (!is.na(knotnas)){ | |
return (knotnas/lnotnas) | |
} | |
else{ | |
if (!try2) { | |
return (NA) | |
} | |
else { | |
mc <- median(c,na.rm=TRUE) | |
tmp <- ifelse(!is.na(c),c,mc) # fill gaps with some value, median as now | |
tmp <- diff(tmp) | |
tmp <- tmp>-1 | |
for(j in which(tmp == FALSE)) { #make waves | |
tmp[j] <- tmp[j+1] == FALSE | |
} | |
tmp <- ifelse(tmp,1,NA) | |
return (has_waves(tmp,try3)) | |
} | |
} | |
} | |
} | |
} | |
} | |
#test | |
has_waves(1) | |
has_waves(c( 1, 1,NA, 1, 1,NA, 1, 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment