Skip to content

Instantly share code, notes, and snippets.

@pads
Created April 3, 2015 10:05
Show Gist options
  • Save pads/bb1451598a993a1b0cef to your computer and use it in GitHub Desktop.
Save pads/bb1451598a993a1b0cef to your computer and use it in GitHub Desktop.
Processing some CSV files for some Psychology PhD statistics work
require 'csv'
# Iterate through each CSV file in the current folder
Dir.glob('*.csv') do |csv_filename|
# Create and open a new file to store the modified rows
csv_output_file = CSV.open("modified-#{csv_filename}", 'wb')
# Open the current file by filename
CSV.open(csv_filename, 'r') do |csv_contents|
# Iterate through each row in the CSV file
csv_contents.each do |row|
# Assign the row being read to a new row
output_row = row
# Fetch the column index we are interested in (offset by 1 based)
target_index = row[5]
# Fetch the value we are interested in given the index above
target_value = row[target_index.to_i - 1]
# Append the value as an additional column in the row
output_row << target_value
# Write the row to the output file
csv_output_file << output_row
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment