-1

I read a matlab file with the R.matlab package and get a number from it as a list. I turn it into a numeric:

library(R.matlab)

# simple case: static filename

setwd("C:/Files/Fold")
nc <- readMat('passvar1.mat')

nC <- as.numeric(nc)
nC
## 10

More complex cast: I need to open file in folder in R with nC in name: C:/Files/Coordinates/CoordsRS%nC%.md.txt

All files have same name apart from number, for example:

 C:/Files/Coordinates/CoordsR4.md.txt
 C:/Files/Coordinates/CoordsR10.md.txt

and, I need to apply operation to this file contents (i.e. pass in a parameter to readMat so it can read them dynamically)

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
mil
  • 301
  • 1
  • 2
  • 15
  • @hrbrmstr. I don't think it's duplicate as I tried that. it doesn't work. newC <- lapply("C:/Folder/corrd/*nC.md.txt", read.table) Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'C:/.../*nC.md.txt': Invalid argument – mil Oct 23 '14 at 20:20

1 Answers1

0

It should be easiest to build the file names either with a paste0 or sprintf call. For example

nC <- 10
paste0("C:/Files/Coordinates/CoordsR", nC, ".md.txt")
# [1] "C:/Files/Coordinates/CoordsR10.md.txt"
sprintf("C:/Files/Coordinates/CoordsR%d.md.txt",nC)
# [1] "C:/Files/Coordinates/CoordsR10.md.txt"

sprintf() has many more options when it comes to padding with leading zeros or otherwise formatting the number before inserting into the string. You can then pass these filenames to readMat()

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thank you. I didn't post that I have tried sprintf too and I get what I need but its class is character.> xx <- sprintf("C:/Folder/Coordinates/%s",nC). How to use this char to open this filename in folder? I don't pass filenames to readMat(). i need to read nC from readMat() and use this nC open file in the folder in R. – mil Oct 23 '14 at 20:26
  • 1
    Just use `readMat(xx)` or `read.table(xx)` or however you want to open the file. Why does that not work? What do you want to do with this path? – MrFlick Oct 24 '14 at 06:14
  • Thank you. read.table(xx) did the job. readMat(xx) returns and error:rror in mat5ReadTag(this) : Unknown data type. Not in range [1,19]: 11829 In addition: Warning messages: 1: In readMat5Header(this, firstFourBytes = firstFourBytes) : Unknown endian: -6. Will assume Bigendian. 2: In readMat5Header(this, firstFourBytes = firstFourBytes) : Unknown MAT version tag: 2336. Will assume version 5. – mil Oct 24 '14 at 09:02