# Computer Science Mojo

~ David's Notes on coding, software and computer science

## R writeBin() lookout for data type

Category: R     Tag: R   Math   Errors
By: David     On: Thu 21 July 2016

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.

### 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)
 "numeric"
> mode(a)
 "numeric"
> is.numeric(a)
 TRUE
> is.double(a)
 TRUE
> is.integer(a)
 FALSE
> a = as.integer(a)
> is.numeric(a)
 TRUE
> is.double(a)
 FALSE
> is.integer(a)
 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 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  1065353216
x = c(1,2,3)
con = file("x","wb")
writeBin(x, con, size = 4)
close(con)
```print(readBin(file("x", "rb"), what = "integer", n=10))