3
$\begingroup$

I got a dataset that looks like the following example:

`exampleData = Dataset[{<|"CompanyName" -> "ca", "period" -> 2015, 
"return" -> 0.3456, "ROE" -> 0.3926|>, <|"CompanyName" -> "ca", 
"period" -> 2014, "return" -> 0.2236, "ROE" -> 0.08894|>, <|
"CompanyName" -> "cb", "period" -> 2014, "return" -> 0.0247, 
"ROE" -> 0.1583|>, <|"CompanyName" -> "cb", "period" -> 2015, 
"return" -> 0.01757, "ROE" -> 0.0662|>, <|"CompanyName" -> "cc", 
"period" -> 2015, "return" -> 0.2145, "ROE" -> 0.1171|>, <|
"CompanyName" -> "cc", "period" -> 2014, "return" -> 0.08972, 
"ROE" -> 0.5339|>}]`

What I am trying to do, is applying a function to the dataset that creates as many new columns as their are different values in CompanyName and at the same time fills it with the according dummies, in a way that the result looks like this:

exampleResult = Dataset[{<|"CompanyName" -> "ca", "period" -> 2015, 
"return" -> 0.3456, "ROE" -> 0.3926, "dummyCA" -> 1, 
"dummyCB" -> 0, "dummyCC" -> 0|>, <|"CompanyName" -> "ca", 
"period" -> 2014, "return" -> 0.2236, "ROE" -> 0.08894, 
"dummyCA" -> 1, "dummyCB" -> 0, "dummyCC" -> 0|>, <|
"CompanyName" -> "cb", "period" -> 2014, "return" -> 0.0247, 
"ROE" -> 0.1583, "dummyCA" -> 0, "dummyCB" -> 1, 
"dummyCC" -> 0|>, <|"CompanyName" -> "cb", "period" -> 2015, 
"return" -> 0.01757, "ROE" -> 0.0662, "dummyCA" -> 0, 
"dummyCB" -> 1, "dummyCC" -> 0|>, <|"CompanyName" -> "cc", 
"period" -> 2015, "return" -> 0.2145, "ROE" -> 0.1171, 
"dummyCA" -> 0, "dummyCB" -> 0, "dummyCC" -> 1|>, <|
"CompanyName" -> "cc", "period" -> 2014, "return" -> 0.08972, 
"ROE" -> 0.5339, "dummyCA" -> 0, "dummyCB" -> 0, 
"dummyCC" -> 1|>}]
$\endgroup$
2
$\begingroup$

I am sure there is a better way, but the following does the job:

comps = exampleData[Union, "CompanyName"];
dummies = "dummy" <> ToUpperCase[#] & /@ comps;
funcs = Function[{x, y}, x -> (If[# == y, 1, 0] &)] @@@ Thread[Normal /@ {dummies, comps}];
ds2 = exampleData[All, Key["CompanyName"] /*Association[funcs]];
Dataset[Join @@@ Thread[Normal /@ {exampleData, ds2}]]

Mathematica graphics

Alternatively you can use Boole instead of If to define funcs:

 funcs= Function[{x, y}, x -> (Boole[# == y] &)] @@@ Thread[Normal /@ {dummies, comps}];
$\endgroup$
  • $\begingroup$ This works very well, thank you! $\endgroup$ – Murr Apr 21 '16 at 10:03
  • $\begingroup$ @Murr, my pleasure. Welcome to mma.se. $\endgroup$ – kglr Apr 21 '16 at 10:05

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.