Reading variables from GDX to R

questions about GAMS' tools
Post Reply
Ayman
User
User
Posts: 1
Joined: 1 year ago

Reading variables from GDX to R

Post by Ayman » 1 year 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
Renger
Posts: 187
Joined: 2 years ago

Re: Reading variables from GDX to R

Post by Renger » 1 year ago

Hi Ayman

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

Code: Select all

rgdx.var <- function(varname) {
  var.data <- 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 = "")
    var.data      <- merge(dim, var.data, by.x = "id", by.y = var.colname)
    var.data      <- var.data[, -which(colnames(var.data) == "id")]
  }
  var.data <- var.data[, c(var.dim:1, var.dim + 1)]
  colnames(var.data)[var.dim + 1]  <- c("value")
  colnames(var.data)[var.dim]      <- "field"
  attributes(var.data)$domains     <- varname$domains
  attributes(var.data)$type        <- "variable"
  attributes(var.data)$symName     <- varname$name
  attributes(var.data)$description <- varname$description
  return(var.data)
}
You can now run
RRdf <- var.rgdx(RR)

Hope this helps
Renger

Post Reply