pivot_long(df, id_cols, trait_cols)

Convert a wide species × traits matrix to long format (species, trait, value). Wrapper around reshape2::melt with sensible defaults.

datautility
Args:df — wide data frameid_cols — identifier columnstrait_cols — trait columns to melt
pivot_long <- function(df, id_cols, trait_cols = NULL) {
  if (is.null(trait_cols)) {
    trait_cols <- setdiff(names(df), id_cols)
  }
  out <- reshape(df[, c(id_cols, trait_cols)],
                 varying   = trait_cols,
                 v.names   = "value",
                 timevar   = "trait",
                 times     = trait_cols,
                 direction = "long")
  out$id   <- NULL
  rownames(out) <- NULL
  out[, c(id_cols, "trait", "value")]
}

# Example
pivot_long(iris, id_cols = "Species")