Reading variables from GDX to R

questions about GAMS' tools
Post Reply
Posts: 1
Joined: 2 years ago

Reading variables from GDX to R

Post by Ayman » 2 years ago

I’m working on reading a GDX file into R. I was able to read the parameters as data frames but I’m having problems with reading variables. The command (rgdx) reads in the variables as lists in R with $val and $uels. I would like to match the indexes of the values with their sets in the uels so I can produce a data frame that contains the values of that variables matched correctly to their sets.

This is the R code line:

Code: Select all

RR<- rgdx(gdxfile, list(name="RR"))
The GDX file has a variable by the name "RR".

This results in a big list with values ($val) and indexes ($uel) and I'm trying to combine the two so the values are matched with their indexes.

Any help?

User avatar
Posts: 273
Joined: 2 years ago

Re: Reading variables from GDX to R

Post by Renger » 2 years ago

Hi Ayman

I wrote a little function a few months ago, to do exactly that

Code: Select all

rgdx.var <- function(varname) { <- data.frame(varname$val)
  var.dim <- length(varname$uels)
  domains <- varname$domains
  for (j in (1:(var.dim))) {
    if (domains[j] == "*") {
      domains[j] <- paste("X", j, sep = "")
  for (i in 1:var.dim) {
    dim           <- data.frame(varname$uels[[i]])
    dim$id        <- seq_along(dim[, 1])
    index         <- varname$domains[i]
    colnames(dim) <- c(index, "id")
    var.colname   <- paste("X", i, sep = "")      <- merge(dim,, by.x = "id", by.y = var.colname)      <-[, -which(colnames( == "id")]
  } <-[, c(var.dim:1, var.dim + 1)]
  colnames([var.dim + 1]  <- c("value")
  colnames([var.dim]      <- "field"
  attributes($domains     <- varname$domains
  attributes($type        <- "variable"
  attributes($symName     <- varname$name
  attributes($description <- varname$description
You can now run
RRdf <- var.rgdx(RR)

Hope this helps

Post Reply