I have several files, and I want to extract for each of them a table, and then select just numbers, and keep only rows with five elements.

My code works fine during import

data = Import[#, "Table"] & /@     FileNames["*.txt",
NotebookDirectory[]] ; (*This line import only tables of numerical
values from txt files*)

but if I want to apply selection of numbers to my list of tables, simply doesn't work,

Select[#, NumberQ[#] & ] & /@ data

and I have to specify a level to make it work,

Select[#, NumberQ[#] & ] & /@ data[[1]]

and I am supposed to automate this for twelve tables, rather that typing for each element. Any suggestions what I am doing wrong? I think that my list of tables needs to be specified different, but I don't know how.

  • $\begingroup$ You indeed have to indicate a level to make it work, annd you can do that with Map[foo, table, level] instead of foo/@table. $\endgroup$
    – Wouter
    Commented Jun 2, 2014 at 15:54

1 Answer 1


When working with nested lists, you should check what part of the lists your mapped functions "see". The pure function with Select in

Select[#, ...]& /@ data

will get data[[1]] as an argument (and data[[2]], data[[3]], and so on). Type data[[1]] into the notebook and look what's inside. It is the entire Table imported from one of your .txt files.

You said however, you want to select rows. So what you want is a) go through every file, and then for every file b) go through every row, and Select those matching your cirteria. Thus, you will have two levels of mapping:

Select[#, ...]& /@ #& /@ data

In case you get confused with the meaning of all these #'es, you can also use functions with named arguments instead of pure functions:

Function[{table}, Select[#, ...]& /@ table] /@ data

Note that you do not append a & here because Function is used (& is the short form of Function). Functions with named arguments are particularly useful if you wanted to access table from inside your Select function. If you only had #, you can only access the argument of the innermost pure function.

Finally, you can make it shorter by using Map explicitly instead of /@ and specifiy that the function is to be mapped one level deeper, i.e. level 2 instead of 1:

Map[Select[#, ...]&, data, {2}]

Note the Mathematica level specification {2} which means "only level 2".

I hope I could make this more clear. If you are unclear about any of the italic words, please look them up in the documentation. :)

  • $\begingroup$ Yes it works the Select[#, ...]& /@ #& /@ data the two level of specification. $\endgroup$
    – Kloudpaper
    Commented Jun 4, 2014 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.