Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does split coerce double to integer in R and is there a workaround

One can build dates in R from numeric types, even fractional values. It's not very common, but it happens for instance when averaging dates. Unfortunately, they seem to break split

> as.Date(-1, origin = "1970-01-01")
[1] "1969-12-31"
> as.Date(-1.0001, origin = "1970-01-01")
[1] "1969-12-30"
> split(as.Date(-1, origin = "1970-01-01"), 1)[[1]]
[1] "1969-12-31"
> split(as.Date(-1.0001, origin = "1970-01-01"), 1)[[1]]
[1] "1969-12-31" #this is wrong
> unclass(split(as.Date(-1, origin = "1970-01-01"), 1)[[1]])
[1] -1
> unclass(split(as.Date(-1.0001, origin = "1970-01-01"), 1)[[1]])
[1] -1 #this is "why"

So two dates that were different are made equal by a split. Do people agree that this is a bug or am I missing the deep reason? Any workarounds? Thanks

like image 431
piccolbo Avatar asked Jan 09 '15 23:01

piccolbo


People also ask

How do I separate numeric values in R?

To split a number into digits in R, we can use strsplit function by reading the number with as. character and then reading the output with as. numeric.

How do I convert an int to a double in R?

To convert an integer to double in R, use the as. double() method. The as. double() is an inbuilt R function that converts an integer to the double class.

How do I convert a number to an integer in R?

R – Convert String to Integer To convert String to Integer in R programming, call strtoi() function, pass the string and base values to this function. strtoi(string, base) returns the integer value of the given string with respect to the specified base.

How do you change to double in R?

double() Method in R. as. double is used to convert an integer to double.


1 Answers

For whatever reason, split.Date coerces the Date input to integer:

> split.Date
function (x, f, drop = FALSE, ...) 
{
    y <- split.default(as.integer(x), f, drop = drop)
    for (i in seq_along(y)) class(y[[i]]) <- "Date"
    y
}
<bytecode: 0x2effb98>
<environment: namespace:base>

This is at minimum an infelicity between the function and the documentation, since ?Date says, "the date should be an integer, but this is not enforced in the internal representation.". Some might consider it a bug. I'm not sure.

You can avoid that by calling split.default directly.

> split.default(as.Date(-1.0001, origin = "1970-01-01"), 1)[[1]]
[1] "1969-12-30"
like image 126
Joshua Ulrich Avatar answered Sep 27 '22 00:09

Joshua Ulrich