Search code examples
matrixbinarybinaryfiles

R: Convert binary file to matrix


R: I uploaded a big binary file (numeric, one array) into R with readBin. My data is composed of values bigger than 10000 and values smaller than 10000, like

25685, 5, 6, 2, 1, 5, 46789, 6, 2, 9, 44220, 5, 1, 3, 7, 9, 12, 88952, 6, 8,...

How can I separate the values, so that I can create a matrix?

1: 25685, 5, 6, 2, 1, 5

2: 46789, 6, 2, 9

3: 44220, 5, 1, 3, 7, 9, 12

The separation should be between the last small value and the big value like above.


Solution

  • name<-file(".dat", "rb")
    size<-(file.info("Path/Name.dat")$size)/8
    rB<-readBin(name, numeric(), size, endian="little")
    size<-length(rB)
    sep<-which(rB>10000) # time steps
    len<-diff(sep,1) # lags
    len<-c(len,(length(rB)-tail(sep,1)+1)) # last value
    mat<-matrix(NA,(size-length(sep)+14),4) # matrix
    for(i in 1:(length(sep))) # fill the matrix
    {
    mat[sep[i]:(sep[i]+len[i]-2),1]<-i
    mat[(sep[i]):(sep[i]+len[i]-2),2]<-(1:(len[i]-1))
    mat[(sep[i]):(sep[i]+len[i]-2),3]<-rB[sep[i]]    
    mat[(sep[i]):(sep[i]+len[i]-2),4]<-rB[(sep[i]+1):(sep[i]+len[i]-1)]
    }
    mat<-mat[which(!is.na(mat[,1])),]