views:

436

answers:

3

Here's a (simplification of a) task I do a lot:

1) Import a CSV file like the following:

    1, cat, 10, junk
    2, dog, 20, junk
    3, mouse, 30, junk

2) Remove the fourth column and replace it with twice the third column.

3) Insert a new column that is half the third column.

4) Export to to CSV, ie:

    1, cat, 5, 10, 20
    2, dog, 10, 20, 40
    3, mouse, 15, 30, 60

I gravitate towards Mathematica for this sort of thing when possible since it has, I think, pretty elegant matrix-munging features. But there are probably at least equally slick ways to do such things in perl/python/ruby/etc, that I just don't know. I'm also curious how to do this in R and Matlab, for comparison.

Let's treat this as a rosetta stone question. So please start your answer with the name of the language (one language per answer) and give the complete code for importing, munging, and exporting the CSV files (which should of course match the output in the example above).

+2  A: 

Mathematica

Here's how I would do this in Mathematica, one line per step above. Note the double-transpose trick in the third line since there's only a way to insert rows, not columns.

data = Import["file.csv", "CSV"];
data[[All,4]] = 2*data[[All,3]];
data = Transpose@Insert[Transpose@data, data[[All,3]]/2, 3];
Export["file2.csv", data];
dreeves
+3  A: 
awk '{ print $1 $2 $3 / 2 "," $3 $3 * 2 }' import.csv > export.csv
neoneye
+2  A: 
ruby -n -e "a = split(', '); v = a[2].to_i; puts [a[0], a[1], v / 2, v, v * 2].join(', ')" import.csv > export.csv
neoneye