0
$\begingroup$

I want to import a series of files with similar filenames that change according to a "ticker". An example is filenames A1_data.dat, B2_data.dat, C3_data.dat etc. The ticker is a list of text values ticker={"A1","B2","C3"}

The following line of code works fine, for the appropriate file path (all files are in the same folder).

ticker = {"A1", "B2", "C3"}; Table[Import[FileNameJoin[{"C:\\Users\\Cartman\\Desktop\\data", StringReplace["ticker_data.dat", "ticker" -> ticker[[i]]]}], "Table"], {i, 1, 3}] 

However, I was wondering how this can be written without a loop structure such as Table or Do but by setting an appropriate function and using e.g. Map. The idea is to change the ticker part of the file path in Import

"C:\\Users\\Cartman\\Desktop\\data\\TICKER_data.dat" 
$\endgroup$

2 Answers 2

1
$\begingroup$

Maybe overkill for this example, but there is StringTemplate which I think is made exactly for such use cases:

template = StringTemplate[ "C:\\Users\\Cartman\\Desktop\\data\\`Ticker`_data.dat"] 

then replacing the `Ticker` part will be done like this:

TemplateApply[template, <|"Ticker" -> "A12"|>] 

You can use this in any loop like contruct like e.g.:

ticker={"A1","B2","C3"}; Map[TemplateApply[template,<|"Ticker"->#|>]&,ticker] 
$\endgroup$
1
  • $\begingroup$ Thank you very much. This is closer to my idea because Ican replace Map with MapAt for a specific ticker. $\endgroup$ Commented Jun 28, 2019 at 8:44
1
$\begingroup$

I'm not sure if I'm understanding this properly, but I think this might work for you:

ticker = {"A1", "B2", "C3"}; mydata = Import["C:\\Users\\Cartman\\Desktop\\data\\"<> # <>"_data.dat", "Table"]&/@ticker 

This should do exactly what you have written above. The # acts as a placeholder for something to be slotted in later, the & tells it to slot in whatever comes after, and /@ is just Map like you suggested. The <> is for joining strings.

mydata should now contain 3 tables. One caveat is that if you ever have to import a single file using this method, the /@ will cause there to be an extra layer of brackets, so mydata[[1]] is the actual table.

$\endgroup$
2
  • $\begingroup$ Thank you very much. This is close to what I described but I would also like to use MapAt or a structure like f[ticker_]:=Import[blahblahblah\ticker] $\endgroup$ Commented Jun 28, 2019 at 8:46
  • $\begingroup$ You can easily replace my Map with MapAt if that's what you prefer. mydata = MapAt[Import["C:\\Users\\Cartman\\Desktop\\data\\"<> # <>"_data.dat", "Table"]&, ticker, All] where All can be replaced with whatever specification you want MapAt to have. If you'd prefer some kind of function, then f[ticker_]:=Import["blahblahblah\\"<> ticker <>"_data.dat"]. $\endgroup$ Commented Jun 28, 2019 at 15:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.