4
$\begingroup$

I would like to translate a imported txt file to Dataset.

test = Import["E:\\mathematica\\example.txt", "table", 
       {"FieldSeparators" -> ",", "CharacterEncoding" -> "ASCII"}]

The result is:

{{"naam A", "naam B", "naam C", "naam D"}, {1, 2, 1.2, "a"}, {2, 3, 2.3, "b"}, {3, 4, 2.3, "c"}, {4, 5, 4.5, "d"}, {5, 6, 5.6, "e"}, {6, 7, 6.7, "f"}, {7, 8, 7.8, "g"}, {8, 9, 8.9, "h"}, {9, 10, 9.1, "i"}, {10, 11, 10.1, "j"}}

Now I would like to translate it to Dataset which is new in Methematica 10.0.

dataset = Dataset[{
   <|"naam A" -> 1, "naam B" -> "2", "naam C" -> {1.1}, "naam D" -> {a}|>,
   <|"naam A" -> 2, "naam B" -> "3", "naam C" -> {1.2}, "naam D" -> {b}|>,
   <|"naam A" -> 3, "naam B" -> "4", "naam C" -> {1.3}, "naam D" -> {c}|>,
   ....
   }]

I tried it with the next code:

data = Dataset[<|"key1" -> test[[All, 1]], "key2" -> test[[All, 2]], 
   "key3" -> test[[All, 3]], "key4" -> test[[All, 4]]|>]

This code gives the wrong output. Anyone a suggestion how to do it?

$\endgroup$
  • 1
    $\begingroup$ Where did {1.1} come from? 1.1 does not exist in the Imported data. And is {} necessary? Anyway, you can code like "Module[{header = First@test}, Inner[Rule, header, #, Association] & /@ (Rest@test) ] // Dataset". $\endgroup$ – Tetsuo Ichii Jul 22 '14 at 12:02
  • 1
    $\begingroup$ you could just use SemanticImport which generates a Dataset for you $\endgroup$ – gogoolplex Jul 22 '14 at 12:03
  • $\begingroup$ What error are you getting? "Unknown box name TypeSystem`TypeMap"? $\endgroup$ – mfvonh Jul 22 '14 at 12:12
  • $\begingroup$ @gogoolplex, SemanticImport doesn't guarantee anything and in 10.0.0 is not ready for prime time. $\endgroup$ – alancalvitti Jul 22 '14 at 13:36
7
$\begingroup$

gogoolplex's suggestion to use SemanticImport is probably the easiest solution to your particular problem, but here is a way to assemble a dataset yourself.

table = {{"naam A", "naam B", "naam C", "naam D"}, {1, 2, 1.2, 
"a"}, {2, 3, 2.3, "b"}, {3, 4, 2.3, "c"}, {4, 5, 4.5, "d"}, {5, 6,
 5.6, "e"}, {6, 7, 6.7, "f"}, {7, 8, 7.8, "g"}, {8, 9, 8.9, 
"h"}, {9, 10, 9.1, "i"}, {10, 11, 10.1, "j"}};

With[{header = First@table}, 
  AssociationThread[header -> #] & /@ Rest@table] // Dataset

enter image description here

$\endgroup$
  • $\begingroup$ Try replacing one of the values with missing data, eg the empty String "" and see if SemanticImport still works. $\endgroup$ – alancalvitti Jul 22 '14 at 13:39
  • $\begingroup$ This is also a useful approach if you already have an array of data (i.e. from a database query in SQLExecute) and would like to turn it into a Dataset without reading and writing files. $\endgroup$ – mdeceglie Jul 31 '14 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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