R/from_df.R

Defines functions vol_field_from_df

Documented in vol_field_from_df

# ============================ #
# A field from a data frame    #
# ============================ #

#' Build a field from a long data frame
#'
#' @title Build a field from a long data frame
#' @description Turns a data frame of one row per cell into a [vol_field()],
#'   taking the grid from the distinct values of the three coordinate columns.
#'   Both naming conventions are recognised: longitude, latitude and depth for a
#'   geographic field, and `x`, `y` and `z` for anything else.
#' @param data A data frame with one row per cell.
#' @param value Name of the column holding the quantity. Guessed when absent.
#' @param x,y,z Names of the three coordinate columns. Guessed when absent.
#' @param time Name of a further column, when the frame holds more than one
#'   volume. Guessed when absent.
#' @param at Value of `time` to take. Defaults to the first, and is ignored when
#'   there is no such column.
#' @param name,unit Passed to [vol_field()]. `name` defaults to the value column.
#' @param flip_z Logical. Negate the third coordinate before building, which
#'   turns an axis measured upward into the downward axis the package uses.
#'   Guessed from the column name when `NA`.
#' @return A `vol_field`.
#' @details The three coordinates need not be complete and need not be sorted.
#'   The grid is the sorted distinct value of each column, a cell absent from the
#'   frame becomes `NA`, and a coordinate that repeats to more than one value at
#'   the same position is an error rather than a silent choice between them.
#'
#'   The guesses are conservative and are stated in the message the function
#'   prints when it makes them. A column named `lon`, `long`, `longitude` or `x`
#'   is the first axis; `lat`, `latitude` or `y` the second; `depth`, `dep`,
#'   `lev`, `level`, `z`, `elevation`, `altitude` or `height` the third; `time`,
#'   `t`, `date` or `step` the fourth. The value is whichever numeric column is left,
#'   when exactly one is.
#'
#'   The third axis of this package is positive downward, since it was built for
#'   a depth. A column named `elevation`, `altitude` or `height` is therefore
#'   negated by default, so that a field measured upward arrives the right way
#'   up; pass `flip_z` to say so explicitly for a column whose name does not
#'   announce it.
#'
#'   A frame carrying a time column holds a sequence of volumes and not one, so
#'   `at` picks the one to build. Rendering the sequence is not something this
#'   function does.
#' @examples
#' d <- expand.grid(lon = 1:20, lat = 1:15, depth = seq(0, 100, by = 10))
#' d$value <- with(d, exp(-depth / 40) * sin(lon / 3) * cos(lat / 3) + 2)
#' f <- vol_field_from_df(d)
#' f
#' plot(f, depth = 30)
#' @seealso [vol_field()] for the object and the index order it fixes,
#'   [vol_read_netcdf()] and [vol_read_npy()] for the two file formats,
#'   [vol_payload()] for the step that follows, [shinyVolumr()] for the
#'   application that accepts such a frame as an upload.
#' @export
vol_field_from_df <- function(data, value = NULL, x = NULL, y = NULL, z = NULL,
                              time = NULL, at = NULL, name = NULL, unit = "",
                              flip_z = NA) {
    data <- as.data.frame(data)
    nm <- names(data)
    guessed <- character(0)
    pick <- function(given, patterns, what) {
        if (!is.null(given)) {
            if (!given %in% nm) stop("there is no column named ", given, call. = FALSE)
            return(given)
        }
        i <- which(grepl(patterns, nm, ignore.case = TRUE))
        if (!length(i)) return(NA_character_)
        guessed[[what]] <<- nm[i[1]]
        nm[i[1]]
    }
    xc <- pick(x, "^(lon|long|longitude|x)$", "x")
    yc <- pick(y, "^(lat|latitude|y)$", "y")
    zc <- pick(z, "^(depth|dep|lev|level|z|elevation|altitude|height)$", "z")
    tc <- pick(time, "^(time|t|date|step)$", "time")
    for (a in c(x = xc, y = yc, z = zc))
        if (is.na(a)) stop("cannot find the three coordinate columns among ",
                           paste(nm, collapse = ", "),
                           ". Name them with `x`, `y` and `z`.", call. = FALSE)
    if (is.null(value)) {
        left <- setdiff(nm, c(xc, yc, zc, if (!is.na(tc)) tc))
        left <- left[vapply(data[left], is.numeric, TRUE)]
        if (length(left) != 1L)
            stop("cannot tell which column holds the value; ",
                 if (!length(left)) "no numeric column is left" else
                     paste0("these are left: ", paste(left, collapse = ", ")),
                 call. = FALSE)
        value <- left
        guessed[["value"]] <- value
    }
    if (length(guessed))
        message("Reading ", paste(sprintf("%s from `%s`", names(guessed), guessed),
                                  collapse = ", "))
    if (!is.na(tc)) {
        ts <- sort(unique(data[[tc]]))
        keep <- if (is.null(at)) ts[1] else at
        if (!keep %in% ts) stop("`at` is not a value of `", tc, "`", call. = FALSE)
        if (length(ts) > 1L)
            message("Column `", tc, "` holds ", length(ts), " values; taking ", keep)
        data <- data[data[[tc]] == keep, , drop = FALSE]
    }
    if (is.na(flip_z))
        flip_z <- grepl("^(elevation|altitude|height)$", zc, ignore.case = TRUE)
    zv <- if (flip_z) -data[[zc]] else data[[zc]]

    xs <- sort(unique(data[[xc]])); ys <- sort(unique(data[[yc]]))
    zs <- sort(unique(zv))
    if (nrow(data) > length(xs) * length(ys) * length(zs))
        stop("the frame has more rows than the grid has cells, so a coordinate ",
             "repeats", call. = FALSE)
    i <- match(data[[xc]], xs); j <- match(data[[yc]], ys); k <- match(zv, zs)
    lin <- k + length(zs) * ((j - 1L) + length(ys) * (i - 1L))
    if (anyDuplicated(lin))
        stop("two rows give a value for the same cell", call. = FALSE)
    values <- array(NA_real_, c(length(zs), length(ys), length(xs)))
    values[lin] <- as.numeric(data[[value]])
    geographic <- !is.na(xc) && grepl("^(lon|long|longitude)$", xc, ignore.case = TRUE)
    vol_field(values, lon = xs, lat = ys, depth = zs,
              name = if (is.null(name)) value else name, unit = unit,
              geographic = geographic,
              source = list(name = "data frame",
                            columns = paste(c(value, xc, yc, zc), collapse = ", ")))
}

Try the volumr package in your browser

Any scripts or data that you put into this service are public.

volumr documentation built on Dec. 2, 2026, 5:07 p.m.