[R] How to reconvert binary matrix back to original numeric?

arun smartpink111 at yahoo.com
Mon Dec 2 23:22:46 CET 2013





Hi,
I couldn't reproduce the first part.
Lines1 <- readLines(textConnection("2 5 7 11
1 2 5
5 7 10 12 13")) 

 Max1 <- max(as.numeric(unlist(strsplit(Lines1," "))))
t(sapply(strsplit(Lines1," "), function(x) {x1<- as.numeric(x); x2 <- numeric(Max1); x2[x1]<- 1; x2}))

#or

mat1<- as.matrix(read.table(text=Lines1,header=FALSE,fill=TRUE))
indx <- cbind(as.vector(t(row(mat1))),as.vector(t(mat1)))
indx1 <- indx[!is.na(indx[,2]),]
Binary <- matrix(0,nrow(mat1),max(mat1,na.rm=TRUE))
Binary[indx1] <- 1

apply(!!Binary,1,which)
A.K.


Hi 
When you have data in text file has different length, for example: 
2 5 7 11 
1 2 5 
5 7 10 12 13 

Then you convert them to binary by: 
BinaryI<- as(data, "matrix") 
And you got: 
0 1 0 0 1 0 1 0 0 0 1 0 0 
1 1 0 0 1 0 0 0 0 0 0 0 0 
0 0 0 0 1 0 1 0 0 1 0 1 1 

How to convert them back to 
2 5 7 11 
1 2 5 
5 7 10 12 13 

I tried as.numeric and it didn’t work, and I tried that also with 
as(unlist(mydata), "numeric") 

thanks



More information about the R-help mailing list