Peter Verbeet
Peter Verbeet

Reputation: 1816

using a "pasted" name inside a function

I have a function that computes some things and then assigns that to a matrix. This matrix receives its name from a paste statement (based on some other current values). I then want to assign the dimnames to the matrix, but don't know how to make the pasted name be understood.

Here is what is going on:

function <- someComputations(labs) {
  ### bunch of computations, leading to X, Y, and Z:
  matName <- paste("rhoMat_", X, sep = "") # this yields rhoMat_15 if X equals 15
  assign(matName, Y %*% Z)
  assign(dimnames(matName), labs) # labs is a list of row labels and column labels
  return(matName)
}

This works well, including the first assign statement, and then it breaks down. I have tried all kinds of approaches, such as eval(parse(text = matNum)), as.name(matNum), substitute(matNum), but to no avail. Since I don't know the actual name of the matrix (because matNum is not given), I can't hardcode the name into the function--so I am stuck with its character name matName. How can I make R understand I want to set the dimnames of the matrix rhoMat_15, rather than of matName?

Thanks, Peter

Upvotes: 3

Views: 579

Answers (1)

Jesse Anderson
Jesse Anderson

Reputation: 4603

dimnames(get(matName)) <- labs

Upvotes: 3

Related Questions