You could give them an option to provide either wide or long format; explain the requirements in the documentation; and implement a test near the top of the function, like
library(vetr)
library(magrittr)
vet_stockDF = function(DF){
target = data.frame(
time = Sys.Date()[0L],
stock = character(0),
price = numeric(0),
stringsAsFactors = FALSE
)
vet(target, DF, stop=TRUE)
}
getStockPlot <- function(stocks_df, do_transform = TRUE){
if (do_transform)
stocks_df %<>% gather(stock, price, -time)
vet_stockDF(stocks_df)
plt <- ggplot(data = stocks_df) +
geom_line(aes(x = time, y = price , colour = stock ))
plt
}
Examples:
# pass original data
getStockPlot(stocks)
# pass long data
longstocks = gather(stocks, stock, price, -time)
getStockPlot(longstocks, do_transform = FALSE)
# pass invalid data
library(dplyr)
getStockPlot(mutate(stocks, time = Sys.time()))
# Error in vet(target, DF, stop = TRUE) :
# `class(DF$time)[2]` should be "Date" (is "POSIXt")
The vetr homepage lists alternative packages with similar functionality. I find vetr very convenient for testing DF attributes.