[R] replacing characters in matrix. substitute, delayedAssign, huh?

Duncan Murdoch murdoch.duncan at gmail.com
Mon Jan 30 19:58:23 CET 2012


On 30/01/2012 1:26 PM, Paul Johnson wrote:
> A user question today has me stumped.  Can you advise me, please?
>
> User wants a matrix that has some numbers, some variables, possibly
> even some function names.  So that has to be a character matrix.

It might make more sense for it to be a list-mode matrix.  Lists are 
vectors, and if they have dimension, they are matrices, but the entries 
need not be the same types.

> Consider:
>
> >  BM<- matrix("0.1", 5, 5)
>
> Use data.entry(BM) or similar to set some to more abstract values.
>
> >  BM[3,1]<- "a"
> >  BM[4,2]<- "b"
> >  BM[5,2]<- "b"
> >  BM[5,3]<- "d"
> >  BM
>       var1  var2  var3  var4  var5
> [1,] "0.1" "0.1" "0.1" "0.1" "0.1"
> [2,] "0.1" "0.1" "0.1" "0.1" "0.1"
> [3,] "a"   "0.1" "0.1" "0.1" "0.1"
> [4,] "0.1" "b"   "0.1" "0.1" "0.1"
> [5,] "0.1" "b"   "d" "0.1" "0.1"
>
> Later on, user code will set values, e.g.,
>
> a<- rnorm(1)
> b<- 17
> d<- 4
>
> Now, push those into "BM", convert whole thing to numeric
>
> newBM<- apply(BM, c(1,2), as.numeric)
>
> and use newBM for some big calculation.
>
> Then re-set new values for a, b, d, do the same over again.
>
> I've been trying lots of variations on parse, substitute, and eval.
>
> The most interesting function I learned about this morning was delayedAssign.
> If I had only to work with one scalar, it does what I want
>
> >  delayedAssign("a", whatA)
> >  whatA<- 91
> >  a
> [1] 91
>
> I can't see how to make that work in the matrix context, though.
>
> Got ideas?

I don't think delayedAssign is what you want:  it creates "promises", 
and promises can only be evaluated once.  You want language entries in 
your matrix, and you want to use eval() to evaluate them.   (Or 
character entries, and use Henrik's parseAndEval.)

Duncan Murdoch



More information about the R-help mailing list