5

The code given below is to convert binary files from float32 to 16b with scale factor of 10. I am getting error of invalidation of %d.

setwd("C:\\2001")
for (b in paste("data", 1:365, ".flt", sep="")) {
   conne <- file(b, "rb")
   file1<- readBin(conne, double(), size=4,  n=360*720, signed=TRUE)
   file1[file1 != -9999] <- file1[file1 != -9999]*10
   close(conne)
   fileName <- sprintf("C:\\New folder (11)\\NewFile%d.bin", b)
   writeBin(as.integer(file1), fileName, size = 2) 
}

Result:

Error in sprintf("C:\\New folder (11)\\NewFile%d.bin",  : 
invalid format '%d'; use format %s for character objects

I used %s as suggested by R.But the files from 1:365 were totally empty

sacvf
  • 2,463
  • 5
  • 36
  • 54
  • 1
    %d is invalid because (as R suggested) you are giving it a character vector (e.g. "data1.flt") rather than an integer. You could use `for (i in 1:365) { b <- paste0("data",i,".flt"); ... sprintf("...%d...",i) }` instead, but this is unlikely to solve your real problem, which is currently unreproducible ... – Ben Bolker May 28 '12 at 14:30

1 Answers1

9

The %d is a placeholder for a integer variable inside a string. Therefore, when you use sprintf(%d, var), var must be an integer.

In your case, the variable b is a string (or a character object). So, you use the placeholder for string variables, which is %s.

Now, if your files are empty, there must be something wrong elsewhere in your code. You should ask another question more specific to it.

erickrf
  • 2,069
  • 5
  • 21
  • 44