Ask Your Question
0

Reading a table to vectors

asked 2013-04-17 06:34:21 +0100

Jaakko Seppälä gravatar image

updated 2013-04-17 11:21:37 +0100

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 flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
0

answered 2013-04-17 10:29:29 +0100

calc314 gravatar image

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[0] 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
edit flag offensive delete link more
0

answered 2013-04-17 11:00:07 +0100

ndomes gravatar image

updated 2013-04-17 11:12:06 +0100

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[0],rows[1],rows[2])
print list_of_tuples
a = vector(list_of_tuples[0])  # and so on
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-04-17 06:34:21 +0100

Seen: 992 times

Last updated: Apr 17 '13