How to resolve the algorithm Merge and aggregate datasets step by step in the Perl programming language
How to resolve the algorithm Merge and aggregate datasets step by step in the Perl programming language
Table of Contents
Problem Statement
Merge and aggregate datasets
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient.
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
visits.csv file contents:
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Merge and aggregate datasets step by step in the Perl programming language
Source code in the perl programming language
#!/usr/bin/perl
my $fmt = '| %-11s' x 5 . "|\n";
printf $fmt, qw( PATIENT_ID LASTNAME LAST_VISIT SCORE_SUM SCORE_AVG);
my ($names, $visits) = do { local $/; split /^\n/m, <DATA> };
my %score;
for ( $visits =~ /^\d.*/gm )
{
my ($id, undef, $score) = split /,/;
$score{$id} //= ['', ''];
$score and $score{$id}[0]++, $score{$id}[1] += $score;
}
for ( sort $names =~ /^\d.*/gm )
{
my ($id, $name) = split /,/;
printf $fmt, $id, $name, ( sort $visits =~ /^$id,(.*?),/gm, '' )[-1],
$score{$id}[0]
? ( $score{$id}[1], $score{$id}[1] / $score{$id}[0])
: ('', '');
}
__DATA__
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
You may also check:How to resolve the algorithm MD5 step by step in the J programming language
You may also check:How to resolve the algorithm Terminal control/Hiding the cursor step by step in the Perl programming language
You may also check:How to resolve the algorithm Gray code step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm OpenGL step by step in the J programming language
You may also check:How to resolve the algorithm Sparkline in unicode step by step in the Raku programming language