tonyfischetti/assertr

Coercion checking

Closed this issue · 1 comments

I sometimes want to make sure a certain data.frame has specific columns, and they have specific types. The most polite way of doing this is to coerce the columns to the type I expect, rather than making the caller do it:

# Kind of harsh:
stopifnot(inherits(df, 'data.frame'))
stopifnot(all(c('datetime', 'value') %in% names(df)))
stopifnot(inherits(df$datetime, 'POSIXct'))

# A little kinder:
df <- as.data.frame(df)
stopifnot(all(c('datetime', 'value') %in% names(df)))
df$datetime <- as.POSIXct(df$datetime)

That gets kind of verbose, though. Everything has to be mentioned multiple times. It would be cool if assertr had some sugar for this use case, maybe something like:

df %<>%
  validate(has_all_names('datetime', 'value')) %>%
  coerce('datetime', as.POSIXct)

Any sympathy for that point of view?

That sounds like it would be helpful sugar but does that fit in with the focus on validation? That might be something better suited for an add-on package. Although, maybe, a is_coerceable predicate might be cool. What do you think?

Thanks for the feedback :)