Writing numeric vs. writing integer to a binary file in R
I want to write integer numbers to a binary file in R, using writeBin. Does it make a difference if I represent them as numeric or as integers? (I want to have a file that is as small as possible but I do not have to use size=... as a parameter.) Is there a command in R that gives the number of bytes on开发者_StackOverflow社区 which a type is represented? Thanks!
The documentation gives the sizes (4 bytes for "integer" type and 8 bytes for "numeric"). You can get various .Machine
parameters including .Machine$$sizeof.long and .Machine$integer.max, but I do not see a "sizeof" value for integer.
You can also do truncation by asserting integer storage mode:
> x <- 23.5
> storage.mode(x) <- "integer"
> x
[1] 23
In R, integers use 4 bytes, and doubles (numerics) use 8 bytes.
If you have a vector of "numbers", and you want to write them as integers then first coerce them to integers like this:
x <- c(3,9,14) # These are actually doubles
writeBin(as.integer(x), "foo.bin") # Coerce to integers before writing!
精彩评论