R writeBin() lookout for data type
R uses "Numeric" as it's default type for numbers. This can sometimes lead to confusion and errors when a specific type is needed. In this example the writeBin() function is used to write data to binary.
Reading
Numeric
Unlike python, which has "four distinct numeric types: plain integers, long integers, floating point numbers, and complex numbers", R uses "Numeric" as it's default type for numbers, which has double-precision. This can bring surprises. From inside-r.org R numeric : "is.numeric returns TRUE if its argument is of mode "numeric" (type "double" or type "integer") and not a factor" :
> a = 3
> class(a)
[1] "numeric"
> mode(a)
[1] "numeric"
> is.numeric(a)
[1] TRUE
> is.double(a)
[1] TRUE
> is.integer(a)
[1] FALSE
> a = as.integer(a)
> is.numeric(a)
[1] TRUE
> is.double(a)
[1] FALSE
> is.integer(a)
[1] TRUE
writeBin()
The type of the number is important when using the function writeBin() to write data to binary, and passing that file to a different program or programming language. One should be careful to convert the data to the wanted type before running writeBin():
x = as.integer(x)
con = file("a","wb")
writeBin(x, con)
close(con)
As writBin() does not have a parameter to specify the type you want (setting size = 4
for integer will not convert the type):
#yes : gives [1] 1 2 3
x = c(1,2,3)
x = as.integer(x)
con = file("x","wb")
writeBin(x, con)
close(con)
readBin("x", what = "integer", n =3)
# nope : gives [1] 1065353216
x = c(1,2,3)
con = file("x","wb")
writeBin(x, con, size = 4)
close(con)
readBin("x", what = "integer")
You also need to specify the correct type when calling readBin() to read the data back into R
print(readBin(file("x", "rb"), what = "integer", n=10))