Many Julia programs involve the input and output of files. When analyzing a dataset, that dataset file will need to be pulled into your program (input). If you want to see the results of your analysis, your program will need an output.
This section provides the syntax for inputing files (reading) and outputting results (writing) use base Julia (i.e., no packages such as CSV.jl).
UC Irvine Machine Learning Repository: Adult Data Set
# process_file.jl# Tabulate and report counts for sex in Adult Data Set# https://archive.ics.uci.edu/ml/datasets/adult# relative path of filedata_file =open("_data/adult/adult.data","r")# absolute path of file# data_file = open("/Users/user/data/adult/adult.data", "r")# initialize collection (dictionary for tabulating counts)gender_dict =Dict()# read each line, extract sex, and keep track of countsfor line inreadlines(data_file)# skip empty linesifisempty(line)continueend# split line into array, based on delimiter (comma and space) line_array =split(line,", ")# tabulate the counts for gender gender = line_array[10]ifhaskey(gender_dict, gender) gender_dict[gender] +=1else gender_dict[gender] =1endend# report total countsprintln("Sort by key (alphabetical):")for gender inkeys(gender_dict)println(" $gender = $(gender_dict[gender])")end# report total counts by key, in reverse orderprintln("Sort by key (reverse alphabetical):")for gender insort(collect(keys(gender_dict)), rev=true)println(" $gender = $(gender_dict[gender])")end# report total counts by value, in reverse order (send output to file)output_file =open("process_file_output.txt","w")println("Sort by value (reverse numerical):")for (count, gender) insort(collect(zip(values(gender_dict),keys(gender_dict))), rev=true)println(" $gender = $(gender_dict[gender])")write(output_file,"$gender = $count\n")end
Output
Sort by key (alphabetical): Female =10771 Male =21790Sort by key (reverse alphabetical): Male =21790 Female =10771Sort by value (reverse numerical): Male =21790 Female =10771
Terminal
$ julia process_file.jlSort by key (alphabetical): Female =10771 Male =21790Sort by key (reverse alphabetical): Male =21790 Female =10771Sort by value (reverse numerical): Male =21790 Female =10771$ ls -1process_file.jlprocess_file_output.txt$ more process_file_output.txtMale =21790Female =10771
Exercises
Analyze the MIMIC-IV Demo Files Using Julia - Forthcoming!
Analyze the SyntheticRI Demo Files Using Julia - Forthcoming!