It seems pretty clear that R strings can't have nul characters. (ref: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Quotes.html ). Problem is, I need to output some nuls to a file. Below is what I wrote when I didn't know I had a problem, and it works file when my mismatched value is any other character.
The purpose of the code is to take a 2d matrix and output a 1d character string where hits are labelled with hex 80 and mismatches are hex 0 (nul). If R doesn't allow strings to contain NUL, what is the "R" way to do this?
mat<-matrix(c(0,0,0, 0,0,0, 1,0,0),nrow=3,ncol=3)
PrintCellsWhere<-function(mymat=matrix(),value=-1) {
outputstring<-""
for(j in 1:ncol(mymat)) {
for(i in 1:nrow(mymat)) {
if(mymat[i,j]==value) {
outputstring<-paste0(outputstring,"\x80")
} else{
outputstring<-paste0(outputstring,"\x00")
}
}
}
return(outputstring)
}
PrintCellsWhere(mymat=mat,value=1)
Error message reported : Error: nul character not allowed
The end goal is to output to a file this data construct with nuls in it. I thought I was going to use writeLines...
(Added a better code example)
You can't have nuls in strings, but you can have a raw vector that has a 0 byte. For example you could change your function to
PrintCellsWhere<-function(mymat=matrix(), value=-1) {
as.raw(ifelse(mymat==value, 128,0))
}
Note the double loop is not necessary at all in R. This will return a "raw" byte vector in R. You can write that to a file with something like
writeBin(PrintCellsWhere(mat, 1), "test.bin")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.