# Reading a table to vectors

I have a csv-file and I have read this in R code read.delim("file:///home/jaakko/Downloads/pcb.dat",header=T , dec = "," , sep = "\t")

This outputs the data like

      A     B      C      D        E
1    11    22.33 21.3   23.23  23.43
2    34     64   664    0.340  0.236
3    3.29  1.150 0.134  1.540  24.9655
...
69   34     123   23     12     23.344


Is there an easy way to split that data to vectors? Like A <- c(11, 34, 3.29, ..., 34), B <- c(22.33, 64, 1.150, ..., 123),...,E <- c(23.43, 0.236, 24.9655, ..., 23.344)

I'm not sure if R-code output can be used as sage-code input, do formatting by Python and then convert code back to R.

Edit. Sorry, I forgot to say that I read the data as in R-mode.

edit retag close merge delete

Sort by » oldest newest most voted

If you are working from a matrix and want (column) vectors, you can do:

a=matrix([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
v0=a[:,0]
v0


If your data is in a list, you can use list comprehensions in python.

a=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
v1=[row for row in a]
v1


You can do it all at once with:

a1=[[r[i] for r in a] for i in range(len(a))]
a1

more Supposed you have a csv file separating the values by comma and separating the rows by semicolon: get rid of the whitespaces, split the csv file into a list of rows, the rows into lists of data, and zip these lists to tuples.

csv_data = """ 0.1 , 2 , 3.01, 4; 5, 6.7, 7, 8;
9, 8, 7, 6 ;   """
csv_data = ''.join(csv_data.split())
rows = csv_data.split(';')
print rows
rows = [row.split(',') for row in rows if row<>'']
rows = [[float(data) for data in rows[k] ] for k in range(len(rows))]
print rows
list_of_tuples = zip(*rows)   # zip(rows,rows,rows)
print list_of_tuples
a = vector(list_of_tuples)  # and so on

more