views:

49

answers:

1

Hello Guys, With psycopg2, i get result of query in this form :

[(15002325, 24, 20, 1393, -67333094L, 38, 4, 493.48763257822799, 493.63348372593703), (15002339, 76, 20, 1393, -67333094L, 91, 3, 499.95845909922201, 499.970048093743), (15002431, 24, 20, 1394, -67333094L, 38, 4, 493.493464900383, 493.63348372593703), (15002483, 76, 20, 1394, -67333094L, 91, 3, 499.959042442434, 499.97304310494502)]

I'm trying to convert this nested tuple/list into R dataframe with RPY2 : with nine column with name, and four row of data (number of element in this nested list ))

But i don't understand how, i'm trying with taggedList (into RPY2 container library) but with no success .. It seems tagged list take one list by one list only.

Thx for help !

+1  A: 
import rpy2.robjects as ro
r=ro.r

data=[(15002325, 24, 20, 1393, -67333094L, 38, 4, 493.48763257822799, 493.63348372593703), (15002339, 76, 20, 1393, -67333094L, 91, 3, 499.95845909922201, 499.970048093743), (15002431, 24, 20, 1394, -67333094L, 38, 4, 493.493464900383, 493.63348372593703), (15002483, 76, 20, 1394, -67333094L, 91, 3, 499.959042442434, 499.97304310494502)]
columns=zip(*data)
columns=[ro.FloatVector(col) for col in columns]
names=['col{i}'.format(i=i) for i in range(9)]
dataf = r['data.frame'](**dict(zip(names,columns)))
print(dataf)

#       col8 col6     col7      col4 col5 col2 col3     col0 col1
# 1 493.6335    4 493.4876 -67333094   38   20 1393 15002325   24
# 2 499.9700    3 499.9585 -67333094   91   20 1393 15002339   76
# 3 493.6335    4 493.4935 -67333094   38   20 1394 15002431   24
# 4 499.9730    3 499.9590 -67333094   91   20 1394 15002483   76

Note that there is an R interface for postgresql, and this may provide a cleaner way than going through Python and rpy2.

If you need Python, another possibility is to figure out the R commands needed to load the data from postgresql, and then call them in Python using ro.r.

unutbu
Thx for answer ! I prefer RPY2 than postgresqlR interface, because of war between different R <-> Pgsql interface.
reyman64