[R] replacing characters in matrix. substitute, delayedAssign, huh?
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Jan 30 19:40:27 CET 2012
On Mon, Jan 30, 2012 at 1:26 PM, Paul Johnson <pauljohn32 at gmail.com> 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.
> 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.
>
You can do this:
> m <- list("a", 1L, 2.5, function(x)x^2)
> dim(m) <- c(2, 2)
> m
[,1] [,2]
[1,] "a" 2.5
[2,] 1 ?
>
> # Run the function in 2,2 passing it argument in 1,2
> m[[2,2]]( m[[1, 2]] )
[1] 6.25
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list