Problem reading .csv file into array

Hello folks,
I’m brand new here, and almost brand new to coding and SC, so hello to everyone, and thanks in advance for any help provided.

here is my code:

x = CSVFileReader.readInterpret("/home/joe/dice_sound/dice_rolls.csv").postcs;
x.postln;
x[1].postln;

Output:
[ [ 1, 5, 3, 6, 2, 2, 1, 4, 5362214 ] ]
-> [ [ 1, 5, 3, 6, 2, 2, 1, 4, 5362214 ] ]
[ [ 1, 5, 3, 6, 2, 2, 1, 4, 5362214 ] ]
-> [ [ 1, 5, 3, 6, 2, 2, 1, 4, 5362214 ] ]
nil
-> nil
-> nil

It seems that there is an extra set of square brackets, which i think is what is stopping me calling the items in the array.

The csv file holds each digit in a separate column with no commas or square brackets. At the moment it only holds these digits, but will eventually hold multiple rows of digits in the exact same format.

What am I doing wrong? Is it something to do with the CSVFileReader?

Hi joe! Welcome to this forum!

Those extra brackets define a multi-dimensional array: CSVFileReader stores an array for each row of data present in the file, and all those arrays together form an array of arrays (a.k.a 2D array).

And it does it even if you have a single row of data. So you have your first (and only) row of data at x[0]

x[0].postln; // -> [ 1, 5, 3, 6, 2, 2, 1, 4, 5362214 ]

And you can access your eight numbers with a second index:

// first row, first item
x[0][0].postln; // 1
// first row, second item
x[0][1].postln; // 5
// and so on

x[0], your first row of data, is an array, so it can do everything an array can do:

x[0].reverse // -> [ 5362214, 4, 1, 2, 2, 6, 3, 5, 1 ]
x[0].sum // -> 5362238
x[0].mean // -> 595804.22222222
x[0].sort // -> [ 1, 1, 2, 2, 3, 4, 5, 6, 5362214 ]
x[0].differentiate // -> [ 1, 0, 1, 0, 1, 1, 1, 1, 5362208 ]
// and so on
1 Like

of course, thank you so much, makes complete sense.

1 Like