Commits

Tom Roche  committed f3c0cff

initial commit of R utilities extracted from AQMEII_ag_soil/{combine_EDGAR_and_EPIC_emissions.r,compute_EPIC_emissions.r}

  • Participants
  • Parent commits ec1e3b6

Comments (0)

Files changed (1)

File R_utilities.r

+# miscellaneous R codes used in regridding projects
+# TODO: package my code! see howto, e.g., Wickham project=devtools
+
+# ----------------------------------------------------------------------
+
+# workaround apparent bug in ncdf4
+get.ncdf4.prec <- function(
+  ncvar4 # object of type=ncvar4
+) {
+  # TODO: test argument
+  ncdf4.prec <- ncvar4$prec
+  if (ncdf4.prec == "int") {
+    return("integer")
+  } else {
+    return(ncdf4.prec)
+  }
+}
+
+### Test if argument is zero within tolerance
+is.zero.tol <- function (val, tol = getOption("tolerance")) {
+  if (is.null(tol)) {
+    tol <- 1e-11
+  }
+  abs(val) <= tol
+}
+
+### Test if argument is NA or zero within tolerance
+is.arr.na.or.zero <- function(arr) {
+# # start debugging-----------------------------------------------------
+#  base::cat(this_fn, '::is.arr.na.or.zero: arr==\n')
+#  print(arr)
+# #   end debugging-----------------------------------------------------
+  # bitwise 'or' !
+  is.na(c(arr)) | is.zero.tol(c(arr))
+} # end is.arr.na.or.zero
+
+### FOR USE ONLY IN `if` CONDITIONS:
+### Return TRUE if value is NA or 0, else FALSE.
+### ASSERT: input is numeric (we won't check!)
+is.val.na.or.zero <- function(val) {
+
+# # start debugging-----------------------------------------------------
+#  base::cat(this_fn, '::is.val.na.or.zero: val==\n')
+#  print(val)
+# #   end debugging-----------------------------------------------------
+
+  if (is.na(val)) {
+    TRUE
+  } else {
+    # TODO: add optional tolerance
+    if (val == 0) {
+      TRUE
+    } else {
+      FALSE
+    }
+  }
+} # end is.val.na.or.zero
+
+### FOR USE ONLY IN `if` CONDITIONS, when dealing with data like
+### >  [1] NA NA NA NA  0 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
+### > [26] NA NA NA NA NA NA NA NA NA NA NA  0  0 NA NA NA NA
+### Return TRUE if all elements of a vector are either NA or 0.
+### ASSERT: input is numeric (we won't check!)
+is.vec.na.or.zero <- function(vec) {
+
+# # start debugging-----------------------------------------------------
+#  base::cat(this_fn, '::is.vec.na.or.zero: vec==\n')
+#  print(vec)
+# #   end debugging-----------------------------------------------------
+
+  if        (!sum(!is.na(vec))) {
+    TRUE
+  } else if (sum(subset(vec, !is.na(vec))) == 0) {
+    TRUE
+  } else {
+    FALSE
+  }
+} # end is.vec.na.or.zero