Skip to content

Instantly share code, notes, and snippets.

@jeffreyhanson
Forked from JaszzyJas/DDCalc.R
Last active October 9, 2015 07:05
Show Gist options
  • Save jeffreyhanson/1da46b8319c99114e5dc to your computer and use it in GitHub Desktop.
Save jeffreyhanson/1da46b8319c99114e5dc to your computer and use it in GitHub Desktop.
Random DD stuff
## Define function that will convert temperatures to Celcius and divide by 8 [same as * 1/8] (as each measurement represents 1/8 of a day)
#Note: need to add a part here where any value <0 = 0 and not a negative, as heating DD's are calculated only using the 'above the threshold'
extractDD=function(path) {
# extract values and convert to kelvin
vals=(values(raster(path,varname="TMP"))-273.15)/8
# set any numbers < 0 to zero
if (sum(vals<0)>0) {
vals[which(vals<0)]=0
}
# return error if any NAs
if (sum(is.na(vals))>0)
stop(paste0("this raster has na values: ", path))
# return values
return(vals)
}
@jeffreyhanson
Copy link
Author

The which is unnecessary, you could just use

...
vals[vals<0]=0
...

but it's a habit of mine.

which returns the indices that are true in a vector of logical (T/F) values. Eg. which(c(T,F,T,F)) yields c(1,3).

@JaszzyJas
Copy link

Cant believe you used unnecessary code... thats like 5 extra characters!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment