user189035
user189035

Reputation: 5789

converting string of binary into data matrix in R

How can i turn M unto a 12 by m matrix of numbers (e.g. with one bit per cell):

library(R.utils)
m<-5    
k<-12   
W<-sample(1:(2**m),k)
M<-matrix(intToBin(V),k,1)

Upvotes: 1

Views: 785

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145895

intToBin is returning characters, so use strsplit to break it into individual digits (bits) before putting in a matrix.

m <- 5
k <- 12
W <- sample(1:(2**m), k)
M <- matrix(as.numeric(unlist(strsplit(intToBin(W), ""))), nrow= k, byrow = TRUE)
> M
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    0    0    0    0    0
 [2,]    0    1    1    0    0    0
 [3,]    0    0    0    1    1    0
 [4,]    0    1    0    0    1    1
 [5,]    0    1    0    1    1    0
 [6,]    0    1    1    1    0    0
 [7,]    0    0    0    0    0    0
 [8,]    0    1    1    1    1    0
 [9,]    1    1    0    1    0    1
[10,]    1    0    0    1    1    1
[11,]    0    0    1    1    1    1
[12,]    0    0    1    1    0    1

Upvotes: 1

mnel
mnel

Reputation: 115390

intToBin will return a character string of the binary representation.

You can split this string, convert to integer, then combine the rows.

 M<-do.call(rbind, lapply(strsplit(intToBin(W),''), as.integer))

Upvotes: 2

Related Questions