tidyverts / tsibble

Tidy Temporal Data Frames and Tools
https://tsibble.tidyverts.org
GNU General Public License v3.0
530 stars 49 forks source link

as.character method for interval #225

Closed wkdavis closed 3 years ago

wkdavis commented 4 years ago

I was wondering if you would consider an as.character.interval() method? My specific use-case is that I would like to include the interval in a warning/error message, but cannot do so easily because there is no as.character() method for the class. I found the format.interval() method and it does exactly what I need, it's just slightly less intuitive (than as.character()) and doesn't play well with other functions that expect an as.character() method (like warning and error). I think the implementation could be as simple as assigning the format() method to as.character() as well, something like: as.character.interval <- format.interval. Below is a brief MRE of how I am trying to use the interval in a warning.

library(tsibble)
#> Warning: package 'tsibble' was built under R version 3.6.2
ivl <- tsibble::new_interval(month = 1, week = 1)

Calling the warning function throws an error because the as.character method doesn't exist.

warning("myfun(x) only supports monthly intervals, but ",
        "`interval(x) == ", ivl, "`")
#> Error: Can't convert <interval> to <character>.

as.character(ivl)
#> Error: Can't convert <interval> to <character>.

I can wrap my interval in format because that method returns a character.

warning("myfun(x) only supports monthly intervals, but ",
        "`interval(x) == '", format(ivl), "'`")
#> Warning: myfun(x) only supports monthly intervals, but `interval(x) == '1M 1W'`

but I feel that is less intuitive than as.character, which could easily be created from the format method.

as.character.interval <- tsibble:::format.interval

as.character(ivl)
#> [1] "1M 1W"

Now warning can be invoked.

warning("myfun(x) only supports monthly intervals, but ",
        "`interval(x) == '", ivl, "'`")
#> Warning: myfun(x) only supports monthly intervals, but `interval(x) == '1M 1W'`

Created on 2020-10-08 by the reprex package (v0.3.0)

earowang commented 4 years ago

For your specific case used for warning() and stop(), I'd suggest to use format() because it is formatting. If there'd be as.character() for <interval>, it'd probably be translated into a verbose form, i.e. 1 Month 1 Week.

earowang commented 3 years ago

I can't find some compelling cases for coercing interval to other classes, and hence closed for now. If there are in the future, please open a new ticket on interval coercion.