How to arrange RPostgreSQL query and create covariance matrix in R

105 views Asked by At

I want to create a covariance matrix from a data frame which is not yet suitable for creating one.

After using RPostgreSQL to query the database I have a data frame of the following type:

pg_id item_id                        value   date
1     67808755896                    23.5    2016-11-12 
2     223337345                      0       2016-11-12 
3     254337000000                   1       2016-11-12 
4     34604777037                    0       2016-11-12 
5     142223438000                   14.3    2016-11-12 
6     170555690000                   22      2016-11-12

The entire data frame is of ~500 000 rows with roughly 16 000 item_id's. The item_id's are repeated (looking back a couple of months here).

What I want to do eventually is to create a covariance matrix for the values of the item_id's.

In order to to so, as a first step I want to re-arrange the data frame in a way that I end up with a data frame that would look like the following:

               item_id
   date          67808755896 223337345  254337000000  ...
   2016-11-12    value       value      value 
   2016-11-12    value       value      value               
   2016-11-12    value       value      value        
   2016-11-12    value       value      value      
   2016-11-12    value       value      value         
   2016-11-12    value       value      value 

My problem is, that I don't know of a way to reorder the data frame the way I need to.

If there is a SQL query that would give me the option at the time of retrieval to get the desired structure, I guess that would be best.

Within R I tried a couple of things from using melt as well as spread but the computation seemed to be to heavy for my local mac which the last time I tried it just shut down at some point.

Thanks in advance for any help!

2

There are 2 answers

2
lukeA On BEST ANSWER

In R, this should run pretty fast:

library(data.table)
set.seed(1)
n_items <- 15996L; n_days <- floor(500000/n_items)
df <- data.frame(
  item_id = 1:n_items,
  date = rep(seq(Sys.Date(), Sys.Date()+n_days, by=1), each=n_items)
)
df$value <- runif(nrow(df))
dim(df)
# [1] 511872       3
uniqueN(df$item_id)
# [1] 15996
setDT(df)
system.time(wide <- dcast(df, date~item_id, value.var = "value", fun.aggregate = mean))
       # User      System verstrichen 
       # 0.19        0.00        0.20 
wide[1:5, 1:5]
#          date          1         2          3         4
# 1: 2017-01-05 0.26550866 0.3721239 0.57285336 0.9082078
# 2: 2017-01-06 0.09235838 0.3801334 0.03702181 0.5900971
# 3: 2017-01-07 0.24687042 0.9922133 0.53181526 0.5044988
# 4: 2017-01-08 0.29523145 0.2263145 0.33291640 0.1165338
# 5: 2017-01-09 0.83870267 0.3274892 0.95595348 0.3889042
0
Yasir Kaheil On

Look into table (your data frame)