显然,R字符串不能包含nul字符。(参考:https://stat.ethz.ch/R-manual/R-devel/library/base/html/Quotes.html)。问题是,我需要将一些nul输出到文件中。以下是我不知道遇到问题时写的内容,当我的不匹配值是任何其他字符时,该文件将起作用。
该代码的目的是获取2d矩阵并输出一个1d字符串,其中的命中标记为十六进制80,不匹配项为十六进制0(nul)。如果R不允许字符串包含NUL,执行此操作的“ R”方式是什么?
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)
报告错误消息:错误:不允许使用nul字符
最终目标是将其中包含nul的此数据构造输出到文件中。我以为我要使用writeLines ...
(添加了更好的代码示例)
字符串中不能包含nul,但是可以有一个0字节的原始向量。例如,您可以将功能更改为
PrintCellsWhere<-function(mymat=matrix(), value=-1) {
as.raw(ifelse(mymat==value, 128,0))
}
请注意,R中根本不需要双循环。这将在R中返回“原始”字节向量。您可以使用类似以下内容的方法将其写入文件
writeBin(PrintCellsWhere(mat, 1), "test.bin")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句