-
Notifications
You must be signed in to change notification settings - Fork 0
/
gplyr.rsc
1303 lines (1075 loc) · 34.7 KB
/
gplyr.rsc
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Creates a new class of object called a data_frame.
Allows tables and other data to be loaded into memory
and manipulated more easily than a standard TC view.
Designed to mimic components of R packages `dplyr`
and `tidyr`.
tbl
Options Array
Optional argument to load table data upon creation
If null, the data frame is created empty
Create a data_frame by calling
df = CreateObject("data_frame")
This package is open source and hosted here:
https://github.com/dkyleward/gplyr
*/
Class "df" (tbl)
init do
self.tbl = CopyArray(tbl)
self.check()
self.groups = null
EndItem
/*
Tests to see if there is any data. Usually called to stop other methods
*/
Macro "is_empty" do
if self.tbl = null then return("true") else return("false")
EndItem
/*
Checks a column name to see if it is reserved. If so, the name
is bracketed.
Returns
field_name
The field name with brackets if appropriate.
*/
Macro "check_name" (field_name) do
a_reserved = {"length"}
field_name = if self.in(field_name, a_reserved)
then "[" + field_name + "]"
else field_name
return(field_name)
EndItem
/*
This creates a complete copy of the data frame. If you try
new_df = old_df
you simply get two variable names that point to the same object.
Instead, use
new_df = old_df.copy()
*/
Macro "copy" do
new_df = CreateObject("df")
a_properties = GetObjectVariableNames(self)
for p = 1 to a_properties.length do
prop = a_properties[p]
type = TypeOf(self.(prop))
new_df.(prop) =
if type = "array" then CopyArray(self.(prop))
else if type = "vector" then CopyVector(self.(prop))
else self.(prop)
end
return(new_df)
EndItem
/*
Either:
Returns vector of all column names
Sets all column names
Use rename() to change individual column names
names
Array or vector of strings
If provided, the method will set the column names instead of
retrieve them
*/
Macro "colnames" (names) do
// Argument checking
if self.is_empty() then return()
if names <> null then do
if TypeOf(names) = "vector" then names = V2A(names)
if TypeOf(names) <> "array" then
Throw("colnames: if provided, 'names' argument must be a vector or array")
if names.length <> self.ncol() then
Throw("colnames: 'names' length does not match number of columns")
end
if names = null then do
for c = 1 to self.ncol() do
a_colnames = a_colnames + {self.tbl[c][1]}
end
end else do
for c = 1 to names.length do
self.tbl[c][1] = names[c]
end
end
if names = null then return(A2V(a_colnames))
EndItem
/*
Returns number of columns
*/
Macro "ncol" do
if self.is_empty() then return()
return(self.tbl.length)
EndItem
/*
Returns number of rows
*/
Macro "nrow" do
if self.is_empty() then return()
return(self.tbl[1][2].length)
EndItem
/*
Checks that the data frame is valid
*/
Macro "check" do
if self.is_empty() then return()
// Make sure that tbl property is an array
if TypeOf(self.tbl) <> "array" then Throw("'tbl' property is not an array")
// Convert all columns to vectors and check length
for i = 1 to self.tbl.length do
colname = self.check_name(self.tbl[i][1])
// Type check
type = TypeOf(self.tbl.(colname))
if type <> "vector" then do
if type <> "array"
then self.tbl.(colname) = {self.tbl.(colname)}
self.tbl.(colname) = A2V(self.tbl.(colname))
end
// Length check
if self.tbl.(colname).length <> self.nrow() then
Throw("check: '" + colname + "' has different length than first column")
end
EndItem
/*
Adds a field to the data frame
vector
Array or Vector
*/
Macro "mutate" (name, vector) do
self.tbl.(name) = vector
self.check()
EndItem
/*
Changes the name of a column in a table object
current_name
String or array of strings
current name of the field in the table
new_name
String or array of strings
desired new name of the field
if array, must be the same length as current_name
*/
Macro "rename" (current_name, new_name) do
// Argument checking
if TypeOf(current_name) <> TypeOf(new_name)
then Throw("rename: Current and new name must be same type")
if TypeOf(current_name) <> "string" then do
if TypeOf(current_name[1]) <> "string"
then Throw("rename: Field name arrays must contain strings")
if current_name.lenth <> new_name.length
then Throw("rename: Field name arrays must be same length")
end
// If a single field string, convert string to array
if TypeOf(current_name) = "string" then do
current_name = {current_name}
new_name = {new_name}
end
for n = 1 to current_name.length do
cName = current_name[n]
nName = new_name[n]
for c = 1 to self.tbl.length do
if self.tbl[c][1] = cName then self.tbl[c][1] = nName
end
end
EndItem
/*
file
String
full path of csv file
append
True/False
Whether to append to an existing csv (defaults to false)
*/
Macro "write_csv" (file, append) do
// Check for required arguments
if file = null then Throw("write_csv: no file provided")
if Right(file, 3) <> "csv"
then Throw("write_csv: file name must end with '.csv'")
if append <> null and !self.in(append, {"a", "w"})
then Throw("write_csv: 'append' must be either 'a', 'w', or null")
// Check validity of table
self.check()
// Open a csv file for writing
if append then file = OpenFile(file, "a")
else file = OpenFile(file, "w")
// Write the row of column names
colnames = self.colnames()
for i = 1 to colnames.length do
if i = 1 then firstLine = colnames[i]
else firstLine = firstLine + "," + colnames[i]
end
WriteLine(file, firstLine)
// Write each remaining row
for r = 1 to self.nrow() do
line = null
for c = 1 to colnames.length do
colname = self.check_name(colnames[c])
vec = self.tbl.(colname)
type = vec.type
strVal = if type = "string" then vec[r]
else String(vec[r])
line = if c = 1 then strVal
else line + "," + strVal
end
WriteLine(file, line)
end
CloseFile(file)
EndItem
/*
Creates a bin file by first creating a csv (write_csv) and then
exporting that to a bin file.
file
String
full path of bin file
*/
Macro "write_bin" (file) do
// Argument check
if file = null then Throw("write_bin: no file provided")
if Right(file, 3) <> "bin"
then Throw("write_bin: file name must end with '.bin'")
// First write to csv
csv_file = Substitute(file, ".bin", ".csv", )
self.write_csv(csv_file)
// Open and export that csv to a bin
view = OpenTable("csv", "CSV", {csv_file})
ExportView(view + "|", "FFB", file, , )
// Clean up workspace
CloseView(view)
DeleteFile(csv_file)
DeleteFile(Substitute(csv_file, ".csv", ".DCC", ))
EndItem
/*
Converts a view into a table object.
Useful if you want to specify a selection set.
MacroOpts
view
String
TC view name
set
Optional string
set name
fields
Optional string or array/vector of strings
Array/Vector of columns to read. If null, all columns are read.
*/
Macro "read_view" (MacroOpts) do
view = MacroOpts.view
set = MacroOpts.set
fields = MacroOpts.fields
// Check for required arguments and
// that data frame is currently empty
if view = null
then Throw("read_view: Required argument 'view' missing.")
if !self.is_empty() then Throw("read_view: data frame must be empty")
if fields <> null then do
if TypeOf(fields) = "string" then fields = {fields}
if TypeOf(fields) = "vector" then fields = V2A(fields)
if TypeOf(fields) <> "array"
then Throw("read_view: 'fields' must be string, vector, or array")
end else do
fields = GetFields(view, )
fields = fields[1]
end
for f = 1 to fields.length do
field = fields[f]
// When a view has too many rows, a "???" will appear in the editor
// meaning that TC did not load the entire view into memory.
// Creating a selection set will force TC to load the entire view.
if f = 1 then do
SetView(view)
qry = "Select * where nz(" + field + ") >= 0"
SelectByQuery("temp", "Several", qry)
end
self.tbl.(field) = GetDataVector(view + "|" + set, field, )
end
self.check()
EndItem
/*
This macro takes data from a data frame and puts it into a view. Columns
are created if necessary.
MacroOpts
view
String
TC view name
set
Optional string
set name
fields
Optional string or array/vector of strings
Array/Vector of columns to read. If null, all df columns are written.
*/
Macro "fill_view" (MacroOpts) do
view = MacroOpts.view
set = MacroOpts.set
fields = MacroOpts.fields
// Check for required arguments and
// that data frame is currently empty
if self.is_empty() then Throw("fill_view: data frame is empty")
if view = null
then Throw("fill_view: Required argument 'view' missing.")
if fields <> null then do
if TypeOf(fields) = "string" then fields = {fields}
if TypeOf(fields) = "vector" then fields = V2A(fields)
if TypeOf(fields) <> "array"
then Throw("fill_view: 'fields' must be string, vector, or array")
end else do
fields = self.colnames()
end
for f = 1 to fields.length do
field = fields[f]
if self.tbl.(field).type = "integer" then type = "Integer"
else if self.tbl.(field).type = "string" then type = "Character"
else type = "Real"
a_fields = {{field, type, 8, 2,,,, ""}}
RunMacro("TCB Add View Fields", {vw, a_fields})
SetDataVector(view + "|" + set, field, self.tbl.(field), )
end
EndItem
/*
Simple wrappers to read_view that read bin and csv directly
*/
Macro "read_bin" (file) do
// Check extension
ext = ParseString(file, ".")
ext = ext[2]
if ext <> "bin" then Throw("read_bin: file not a .bin")
opts = null
opts.view = OpenTable("view", "FFB", {file})
self.read_view(opts)
CloseView(opts.view)
EndItem
Macro "read_csv" (file) do
// Check extension
a_parts = ParseString(file, ".")
ext = a_parts[2]
if ext <> "csv" then Throw("read_csv: file not a .csv")
opts = null
opts.view = OpenTable("view", "CSV", {file})
self.read_view(opts)
CloseView(opts.view)
// Remove the .DCC
DeleteFile(Substitute(file, ".csv", ".DCC", ))
EndItem
/*
Reads a matrix file.
file
String
Full file path of matrix
cores
String or array of strings
Core names to read - defaults to all cores
ri and ci
String
Row and column indicies to use. Defaults to the default indices.
all_cells
"Yes" or "No"
Whether to include every ij pair in the data frame. Defaults to "Yes".
Set to "No" to drop cells with missing values.
*/
Macro "read_mtx" (file, cores, ri, ci, all_cells) do
// Check arguments and set defaults if needed
if !self.is_empty() then Throw("read_mtx: data frame must be empty")
a_parts = ParseString(file, ".")
ext = a_parts[2]
if ext <> "mtx" then Throw("read_mtx: file name must end in '.mtx'")
mtx = OpenMatrix(file, )
a_corenames = GetMatrixCoreNames(mtx)
if cores = null then cores = a_corenames
if TypeOf(cores) = "string" then cores = {cores}
if TypeOf(cores) <> "array" then
Throw("read_mtx: 'cores' must be either an array, string, or null")
for c = 1 to cores.length do
if !self.in(cores[c], a_corenames)
then Throw("read_mtx: core '" + cores[c] + "' not found in matrix")
end
{d_ri, d_ci} = GetMatrixIndex(mtx)
if ri = null then ri = d_ri
if ci = null then ci = d_ci
{row_inds, col_inds} = GetMatrixIndexNames(mtx)
if !self.in(ri, row_inds)
then Throw("read_mtx: row index '" + ri + "' not found in matrix")
if !self.in(ci, col_inds)
then Throw("read_mtx: column index '" + ci + "' not found in matrix")
if all_cells = null then all_cells = "Yes"
// Set the matrix index and export to a table
SetMatrixIndex(mtx, ri, ci)
file_name = GetTempFileName(".bin")
opts = null
opts.Complete = all_cells
opts.Tables = cores
CreateTableFromMatrix(mtx, file_name, "FFB", opts)
// Read exported table into view
self.read_bin(file_name)
// Clean up workspace
DeleteFile(file_name)
DeleteFile(Substitute(file_name, ".bin", ".DCB", ))
EndItem
/*
Creates a view based on a temporary binary file. The primary purpose of
this macro is to make GISDK functions/operations available for a table object.
The view is often read back into a table object afterwards.
Returns:
view_name: Name of the view as opened in TrandCAD
file_name: Name of the temporary bin file
*/
Macro "create_view" do
// Convert the data frame object into a CSV
tempFile = GetTempFileName(".bin")
self.write_bin(tempFile)
// Avoid duplciating view names by using an
// odd name and adding a number based on views open.
// Check to make sure view does not already exist.
view_names = GetViews()
if view_names.length = 0 then do
view_name = "gplyr1"
end else do
view_names = view_names[1]
num = view_names.length
exists = "True"
while exists do
num = num + 1
view_name = "gplyr" + String(num)
exists = if (ArrayPosition(view_names, {view_name}, ) <> 0)
then "True"
else "False"
end
end
view_name = OpenTable(view_name, "FFB", {tempFile}, )
return({view_name, tempFile})
EndItem
/*
Only used in development/debugging, an editor is a visible
window in TC that displays the contents of a view. Use this to
see the contents of your data frame in a tabular format.
Calling create_editor automatically generates an error message
to stop the code and allow you to view the table. This also
prevents from ever being used in production code, and it never
should be.
*/
Macro "create_editor" do
{view_name, file_name} = self.create_view()
CreateEditor("data frame", view_name + "|", , )
Throw("Editor created to view\ndata frame contents")
EndItem
/*
Removes field(s) from a table
fields:
String or array of strings
fields to drop from the data frame
*/
Macro "remove" (fields) do
// Argument checking and type handling
if fields = null then Throw("remove: no fields provided")
if TypeOf(fields) = "string" then fields = {fields}
for f = 1 to fields.length do
self.tbl.(fields[f]) = null
end
EndItem
/*
Like dply or SQL "select", returns a table with only
the columns listed in "fields".
fields:
String or array of strings
fields to keep in the data frame
*/
Macro "select" (fields) do
// Argument checking and type handling
if fields = null then Throw("select: no fields provided")
if TypeOf(fields) = "string" then fields = {fields}
data = null
for f = 1 to fields.length do
field = fields[f]
data.(field) = self.tbl.(self.check_name(field))
end
self.tbl = data
EndItem
/*
Checks if a value is listed anywhere in the vector.
find
String, numeric, array, or vector
The value to search for
space
Array, vector, or string
The search space.
If string, `find` must be string.
Returns True/False
*/
Macro "in" (find, space) do
// Argument check
if TypeOf(find) = "vector" then find = V2A(find)
if find = null then Throw("in: 'find' not provided")
if TypeOf(space) = "vector" then space = V2A(space)
if space = null then Throw("in: 'space' not provided")
if TypeOf(space) = "array" and TypeOf(find) <> "array"
then find = {find}
if TypeOf(space) = "string" and TypeOf(find) <> "string"
then Throw("in: if variable 'space' is a string, `find` must be a string")
if TypeOf(space) = "string"
then tf = if Position(space, find) <> 0 then "True" else "False"
else tf = if ArrayPosition(space, find, ) <> 0 then "True" else "False"
return(tf)
EndItem
/*
Establishes grouping fields for the data frame. This modifies the
behavior of summary functions.
*/
Macro "group_by" (fields) do
// Argument checking and type handling
if fields = null then Throw("group_by: no fields provided")
if TypeOf(fields) = "string" then fields = {fields}
self.groups = fields
EndItem
/*
This macro works with group_by() similar to dlpyr in R.
Summary stats are calculated for the columns specified, grouped by
the columns listed as grouping columns in the df.groups property.
(Set grouping fields using group_by().)
agg
Options array listing field and aggregation info
e.g. agg.weight = {"sum", "avg"}
This will sum and average the weight field
The possible aggregations are:
first, sum, high, low, avg, stddev
Returns
A new data frame of the summarized input table object.
In the example above, the aggregated fields would be
sum_weight and avg_weight
*/
Macro "summarize" (agg) do
// Remove fields that aren't listed for summary or grouping
for i = 1 to self.groups.length do
a_selected = a_selected + {self.groups[i]}
end
for i = 1 to agg.length do
a_selected = a_selected + {agg[i][1]}
end
self.select(a_selected)
// Convert the TABLE object into a view in order
// to leverage GISDKs SelfAggregate() function
{view, file_name} = self.create_view()
// Create a field spec for SelfAggregate()
agg_field_spec = view + "." + self.groups[1]
// Create the "Additional Groups" option for SelfAggregate()
opts = null
if self.groups.length > 1 then do
for g = 2 to self.groups.length do
opts.[Additional Groups] = opts.[Additional Groups] + {self.groups[g]}
end
end
// Create the fields option for SelfAggregate()
for i = 1 to agg.length do
name = agg[i][1]
stats = agg[i][2]
proper_stats = null
for j = 1 to stats.length do
proper_stats = proper_stats + {{Proper(stats[j])}}
end
fields.(name) = proper_stats
end
opts.Fields = fields
// Create the new view using SelfAggregate()
agg_view = SelfAggregate("aggview", agg_field_spec, opts)
// Read the view back into the data frame
self.tbl = null
opts = null
opts.view = agg_view
self.read_view(opts)
// The field names from SelfAggregate() are messy. Clean up.
// The first fields will be of the format "GroupedBy(ID)".
// Next is a "Count(bin)" field.
// Then there is a first field for each group variable ("First(ID)")
// Then the stat fields in the form of "Sum(trips)"
// Set group columns back to original name
for c = 1 to self.groups.length do
self.tbl[c][1] = self.groups[c]
end
// Set the count field name
self.tbl[self.groups.length + 1][1] = "Count"
// Remove the First() fields
self.tbl = ExcludeArrayElements(
self.tbl,
self.groups.length + 2,
self.groups.length
)
// Change fields like Sum(x) to sum_x
for i = 1 to agg.length do
field = agg[i][1]
stats = agg[i][2]
for j = 1 to stats.length do
stat = stats[j]
current_field = Proper(stat) + "(" + field + ")"
new_field = lower(stat) + "_" + field
self.rename(current_field, new_field)
end
end
// Clean up workspace
CloseView(view)
CloseView(agg_view)
DeleteFile(file_name)
DeleteFile(Substitute(file_name, ".bin", ".DCB", ))
EndItem
/*
Applies a query to a table object.
query
String
Valid TransCAD query (e.g. "ID = 5" or "Name = 'Sam'")
Do not include "Select * where" in the query string
*/
Macro "filter" (query) do
// Argument check
if query = null then Throw("filter: query is missing")
if TypeOf(query) <> "string" then Throw("filter: query must be a string")
if Proper(Left(query, 6)) = "Select" then
Throw("filter: do not include 'Select * where' in your query")
{view, file} = self.create_view()
SetView(view)
query = "Select * where " + query
SelectByQuery("set", "Several", query)
self.tbl = null
opts = null
opts.view = view
opts.set = "set"
self.read_view(opts)
// Clean up workspace
CloseView(view)
DeleteFile(file)
DeleteFile(Substitute(file, ".bin", ".DCB", ))
EndItem
/*
Joins two data frame objects.
slave_tbl
data frame objects
m_id and s_id
String or array
The id fields from master and slave to use for join. Use an array to
specify multiple fields to join by.
*/
Macro "left_join" (slave_tbl, m_id, s_id) do
// Argument check
if TypeOf(m_id) = "string" then m_id = {m_id}
if TypeOf(s_id) = "string" then s_id = {s_id}
if m_id.length <> s_id.length then
Throw("left_join: 'm_id' and 's_id' are not the same length")
// Create dup_fields
// an array of fields that will be duplicated
// after the join (that aren't in m_id or s_id)
m_fields = V2A(self.colnames())
m_result = CopyArray(m_fields)
s_fields = V2A(slave_tbl.colnames())
s_result = CopyArray(s_fields)
for i = 1 to m_id.length do
m = m_id[i]
s = s_id[i]
pos = ArrayPosition(m_result, {m}, )
m_result = ExcludeArrayElements(m_result, pos, 1)
pos = ArrayPosition(s_result, {s}, )
s_result = ExcludeArrayElements(s_result, pos, 1)
end
if m_result.length > 0 then do
for i = 1 to m_result.length do
field = m_result[i]
if self.in(field, s_result) then dup_fields = dup_fields + {field}
end
end
{master_view, master_file} = self.create_view()
{slave_view, slave_file} = slave_tbl.create_view()
dim m_spec[m_id.length]
dim s_spec[s_id.length]
for i = 1 to m_id.length do
m_spec[i] = master_view + "." + m_id[i]
s_spec[i] = slave_view + "." + s_id[i]
end
jv = JoinViewsMulti("jv", m_spec, s_spec, )
self.tbl = null
opts = null
opts.view = jv
self.read_view(opts)
// JoinViewsMulti() will attach the view names to the m_id and s_id fields
// if they are the same.
// Remove the s_id fields, and clean the m_id fields (if needed)
for i = 1 to m_id.length do
m = m_id[i]
s = s_id[i]
if m = s then do
// Rename master field
current_name = master_view + "." + m
self.rename(current_name, m)
// Delete slave field
self.tbl.(slave_view + "." + s) = null
end else do
// Delete slave field
self.tbl.(s) = null
end
end
// Handle any other duplicate fields.
// Replace the default name with a .x and .y suffix.
for d = 1 to dup_fields.length do
field = dup_fields[d]
current_name = master_view + "." + field
new_name = field + ".x"
self.rename(current_name, new_name)
current_name = slave_view + "." + field
new_name = field + ".y"
self.rename(current_name, new_name)
end
// Clean up the workspace
CloseView(jv)
CloseView(master_view)
DeleteFile(master_file)
DeleteFile(Substitute(master_file, ".bin", ".DCB", ))
CloseView(slave_view)
DeleteFile(slave_file)
DeleteFile(Substitute(slave_file, ".bin", ".DCB", ))
EndItem
/*
Concatenates multiple column values into a single column
cols
Vector or array of strings
column names to unite
new_col
String
Name of new column to place results
sep
String
Separator to use between values
Defaults to `_`
*/
Macro "unite" (cols, new_col, sep) do
// Argument check
if sep = null then sep = "_"
if TypeOf(cols) = "vector" then cols = V2A(cols)
if TypeOf(cols) <> "array"
then Throw("unite: 'cols' must be an array or vector")
if new_col = null then Throw("unite: `new_col` not provided")
if TypeOf(cols) <> "array" then Throw("unite: `cols` must be an array")
for c = 1 to cols.length do
col = self.check_name(cols[c])
vec = self.tbl.(col)
vec = if (vec.type = "string")
then self.tbl.(col)
else String(self.tbl.(col))
self.tbl.(new_col) = if (c = 1)
then vec
else self.tbl.(new_col) + sep + vec
end
EndItem
/*
Opposite of unite(). Separates a column based on a delimiter
col
String
Name of column to seaprate
new_cols
Array of strings
Names of new columns
sep
String
Delimter to use to parse
*/
Macro "separate" (col, new_cols, sep) do
// Argument check
if sep = null then sep = "_"
if col = null then Throw("separate: `col` not provided")
if TypeOf(new_cols) = "vector" then new_cols = V2A(new_cols)
if TypeOf(new_cols) <> "array"
then Throw("separate: 'new_cols' must be an array or vector")
if TypeOf(new_cols) <> "array"
then Throw("separate: `new_cols` must be an array")
vec = self.tbl.(col)
if TypeOf(vec[1]) <> "string" then
Throw("separate: column '" + col + "' doesn't contain strings")
dim array[new_cols.length, self.nrow()]
for r = 1 to self.nrow() do
vec = self.tbl.(col)
string = vec[r]
parts = ParseString(string, sep)
// Error check
if r = 1 then do
if parts.length <> new_cols.length then
Throw("separate: `new_cols` length doesn't match parsed '" + col + "'")
end
for p = 1 to parts.length do
value = parts[p]
// Convert any string-number into a number
if TypeOf(value) = "string" then do
value = if value = "0"
then 0
else if Value(value) = 0
then value
else Value(value)
end
array[p][r] = value
end
end
// fill data frame
for c = 1 to new_cols.length do
self.tbl.(new_cols[c]) = array[c]
end
// remove original column
self.tbl.(col) = null
EndItem
/*
Place holder for notes about spread()
- create columns for each unique value of key
- fill each with values where the key is matched
- create a new field that unites non-key/value columns
- start a new data frame with just that field
- use that to perform joins