I have three big vectors with the same dimension. I need to write them in a binary file with a certain order: two integers followed by a double. Example:
a <- c(1,2,3,4) #integers
b <- c(5,6,7,8) #integers
d <- c(1.32421, 1.42342134123,21.4123412361,1.123412346) #doubles
# desired order:
# 1, 5, 1.32421, 2, 6, 1.42342134123, 3, 7, 21.4123412361, 4, 8, 1.12344112346
I would like doing it witout using a loop. Is it possible? This is my actual code for this example:
con_ <- "a"
file.create(con_)
con <- file(con_,"wb")
for(i in seq(1,length(a))){
ve <- c(a[i],b[i])
writeBin(ve,con, size = 4)
writeBin(d[i],con, size = 8)
}
You can rbind the vectors to get the vectors in the desired order.
c(rbind(a, b, d))
#Similar to
#c(t(cbind(a, b, d)))
#[1] 1.00 5.00 1.32 2.00 6.00 1.42 3.00 7.00 21.41 4.00 8.00 1.12
Note that you can have data of only one class in a vector. So in this example, all of them turn into numeric.
We can do this with order and it should also work when the lengths are not the same
c(a, b, d)[order(c(seq_along(a), seq_along(b), seq_along(d)))]
#[1] 1.000000 5.000000 1.324210 2.000000 6.000000 1.423421 3.000000 7.000000 21.412341 4.000000 8.000000 1.123412
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With