My question is in two parts. The first is about picking discrete elements inside a list of Associations to match a fixed percentage of a final sub-list; the second is about overcoming the rounding problem the first part creates.
I have data in a List of Associations, a portion of which looks like this
{<|"Sector" -> "A", "ID" -> 1101, "Year" -> 1990, "AnnReturn" -> 0.0946|>, <|"Sector" -> "A", "ID" -> 1102, "Year" -> 1990, "AnnReturn" -> 0.0901|>, <|"Sector" -> "A", "ID" -> 1103, "Year" -> 1990, "AnnReturn" -> 0.00876|>, <|"Sector" -> "A", "ID" -> 1104, "Year" -> 1990, "AnnReturn" -> 0.0242|>, <|"Sector" -> "A", "ID" -> 1105, "Year" -> 1990, "AnnReturn" -> 0.0783|>, <|"Sector" -> "A", "ID" -> 1106, "Year" -> 1990, "AnnReturn" -> 0.0433|>, <|"Sector" -> "A", "ID" -> 1107, "Year" -> 1990, "AnnReturn" -> 0.0253|>, <|"Sector" -> "A", "ID" -> 1108, "Year" -> 1990, "AnnReturn" -> 0.1144|>, <|"Sector" -> "A", "ID" -> 1109, "Year" -> 1990, "AnnReturn" -> 0.1036|>, <|"Sector" -> "A", "ID" -> 111, "Year" -> 1990, "AnnReturn" -> 0.1216|>, <<145845>>}
The first Key = Sector has four possibilities, A, B, C and D
I need to compose a sub-list OF UNIQUE VALUES which has a fixed (but uneven) percentage of each sector. Here is an example where the proportions correspond to "A","B","C" and "D"
{0.13, 0.19, 0.28, 0.4}
Note the decimals must add to unity.
So, to be completely tedious, a sub-list of, say, 1033 elements would have
Round[1033 {0.13, 0.19, 0.28, 0.4}]
to get this
(*{134, 196, 289, 413}*)
...which adds to 1032. What I need should be the total sought less the first three proportions, producing the fourth. I am sure there is a better way than this, but this works
Join[Round[1033 #], {1033 - Plus @@ Round[1033 #]}] &[{0.13, 0.19,
0.28}]
@MarcoB suggested this
grupBySec = GroupBy[netLoA, #"Sector" &];
RandomChoice[{0.13, 0.19, 0.28, 0.4} -> grupBySec]
but it only randomizes the sector. It looks like the Documentation for weights but those examples do not use Associations
{0.13, 0.19, 0.28, 0.4}
as weights? $\endgroup$RandomSample
instead ofRandomChoice
. I've updated my answer to reflect that and added a check for duplicates. $\endgroup$