-
Notifications
You must be signed in to change notification settings - Fork 15
/
mungeData.matlab
59 lines (44 loc) · 1.48 KB
/
mungeData.matlab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function newdata = mungeData(data,window,method)
%MUNGEDATA
%
% When there are polls from the last month, take the mean.
% If there is no poll in the last month, use the most recent month, or
% the 2008 results when no poll is available.
% Config for model. Take the average of all polls from the last 'win' days.
if nargin < 2
window = 30;
end
if nargin < 3
method = 'mean';
end
if ischar(method)
method = str2func(method);
end
% Electoral vote data
ev = loadElectoralVotes;
% Munge poll data
states = unique(data.state);
lastDay = max(data.datenum);
newdata.state = cell(51,1);
newdata.p = zeros(51,2);
newdata.npolls = zeros(51,1);
newdata.ev = zeros(51,1);
for ii = 1:length(states)
state = states{ii};
stateIdx = strmatch(state,data.state,'exact');
lastMonthIdx = (lastDay - data.datenum(stateIdx)) < window;
if ~any(lastMonthIdx)
idx = stateIdx(1);
else
idx = stateIdx(lastMonthIdx);
end
p = bsxfun(@rdivide,[data.dem(idx) data.gop(idx)] ,(data.dem(idx)+data.gop(idx)));
n = size(p,1);
p = method(p,1);
newdata.state{ii} = state;
newdata.p(ii,:) = p;
newdata.npolls(ii,:) = n;
idx = strmatch(state,ev.state,'exact');
newdata.ev(ii) = ev.ev(idx);
end
end