#delim ;
prog def cprdhes_hrg;
version 13.0;
*
 Create dataset with 1 obs per episode of care
 and data on Health Resource Geroup (HRG) variables.
 Add-on packages required:
 keyby, chardef
*!Author: Roger Newson
*!Date: 29 January 2019
*;

syntax using [ , CLEAR noKEY DELIMiters(passthru) ENCoding(string) ];
/*
 clear specifies that any existing dataset in memory will be cleared.
 nokey specifies that the new dataset will not be keyed by patid, spno, epikey and d_order.
 delimiters() is passed through to import delimited.
 encoding() is passed through to import delimited as a charset() option.
*/

*
 Input data
*;
import delimited `using', varnames(1) stringcols(_all) charset(`"`encoding'"') `delimiters' `clear';
desc, fu;

* Label variables *;
cap lab var patid "Patient ID";
cap lab var spno "Spell number";
cap lab var epikey "Episode key";
cap lab var domproc "NHS trust derived dominant procedure";
cap lab var hrglate "Latest version of HRG derived by HES";
cap lab var hrglate35 "HRG version 3.5 derived by HES";
cap lab var hrgnhs "NHS trust derived HRG value";
cap lab var hrgnhsvn "Version number of Trust derived HRG";
cap lab var suscorehrg "SUS generated Core Spell HRG";
cap lab var sushrg "SUS generated HRG";
cap lab var sushrgvers "SUS generated HRG version number";
cap lab var hes_yr "Year of HES record (generated by CPRD)";

*
 Convert string variables to numeric if necessary
*;
foreach X in patid spno epikey sushrgvers hes_yr {;
  cap conf string var `X';
  if !_rc {;
    destring `X', replace force;
    charundef `X';
  };
};
charundef _dta *;

*
 Key dataset if requested
*;
if "`key'"!="nokey" {;
  keyby patid spno epikey, fast;
};

*
 Describe dataset
*;
desc, fu;

end;