Skip to content

creating expressions inside loop

2 messages · Jan Goebel, Peter Dalgaard

#
Hello all,

may be someone can give me a hint how to
solve a little problem.

I'm trying to create some expressions inside
a for-loop which i want to evaluate AFTER this
creation loop (but loop specific).

To explain my problem here comes the code:

y.mat <- t(matrix(rep(84:90,8) + as.numeric(gl(8,7)),nrow=7))

# > y.mat[1:2,]
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]   85   86   87   88   89   90   91
# [2,]   86   87   88   89   90   91   92

shift <- list()
for (i in 1:8) {
  shift[[i]] <- expression(
      eval(
           parse(text=paste("cbind(",
                   paste("w1", y.mat[i,],sep="",collapse = ", "),")")
                 )
           )
      )
}
# which gives no error, but
[[1]]
[1] "w189" "w190" "w191" "w192" "w193" "w194" "w195"
[[1]]
[1] "w189" "w190" "w191" "w192" "w193" "w194" "w195"

is all the same, because "i" is fixed by the last value
in the loop. So how can i change
[[1]]
expression(eval(parse(text = paste("cbind(", paste("w1", y.mat[i,], 
    sep = "", collapse = ", "), ")"))))

to an "in-loop evaluating" of
[1] "w189, w190, w191, w192, w193, w194, w195"
  
so that the expression looks like
[[1]]
expression(eval(parse(text = paste("cbind(", 
    "w189, w190, w191, w192, w193, w194, w195", ")"))))


hope this is understandable ;-)

best

jan
#
Jan Goebel <jgoebel at diw.de> writes:
You could use

  substitute(...., list(i=i))

instead of 

  expression(....)

But wouldn't you rather do something like

f <- function(row) {
    n <- paste("w1",row, sep="")
    m <- do.call("cbind", lapply(n, get))
    names(m) <- n
    m
}

apply(y.mat, 1, f)