Need to initiate a for loop
using a vector
argument in pl/r
. The code is as below:
DROP TYPE IF EXISTS tsdata CASCADE;
CREATE TYPE tsdata
AS
(
a text,
b text,
c text,
d text
);
DROP FUNCTION IF EXISTS standard.create_pd_ts(data char, dimnames char);
CREATE FUNCTION standard.create_pd_ts(data char, dimnames char)
RETURNS setof tsdata AS
$$
drv <- dbDriver("PostgreSQL")
conn <- dbConnect(drv, dbname = 'abc')
iq <- paste0("select * from data")
data <-dbGetQuery(conn, iq)
data <- data.frame(coef_db_res_tab)
for(i in 1:length(dimnames)) {
var = dimnames [i]
uniquedim= unique(data[,i])
assign(paste0('dim',i),uniquedim)
}
## save dimensions in a vector
dimvec<-paste0('dim',1:length(dimnames),collapse = ',')
tsdata <- eval(parse(text=paste0("expand.grid(", dimvec,
",stringsAsFactors = FALSE)")))
return(tsdata)
$$
LANGUAGE 'plr';
select
(q).a,
(q).b,
(q).c,
(q).d
from
(
select * from standard.create_pd_ts(‘data’, 'c("a","b","c","d")')
) q ;
The motive of the function is to find unique values of column a, b, c and d; henceforth, store the values for the same in the dimvec vector, thereafter using the unique values of each column to expand grid to create all combinations. Tried a variety of things, but the for loop is not initiating. If I declare the dimnames vector inside the function, it works.
Also tried declaring as array, text, declaring as vector inside the function.
Any help is appreciated.
select
(q).a,
(q).b,
(q).c,
(q).d
from
(
select * from standard.create_pd_ts('data', ARRAY['a','b','c','d'])
) q ;
This works for me. Thanks to my boss :)