Search code examples
rvectorindexingexpressionrep

Generate Vector automatically with expression(X['i,n'])


I'm trying to generate a vector of the length n that should look like this:

(expression(X['n,n'],.....,X['1,n']))

So for example:

n <- 3

I want to have:

(expression(X['3,3'],X['2,3'],X['1,3']))

I tried the following:

n <- 10
y<- c()


for (i in 1:n){
  y[i] <- rep(expression(X['i,n']),1)
}

y

Output:

expression(X["i,n"], X["i,n"], X["i,n"], X["i,n"], X["i,n"], 
    X["i,n"], X["i,n"], X["i,n"], X["i,n"], X["i,n"])

How can I solve this?


Solution

  • Here I use bquote to build the individual expressions and then i use c to combine them.

    n<-5
    do.call(c, 
        lapply(paste(n:1,n, sep=","), 
        function(x) 
            bquote(expression(X[.(x)]))
        )
     )
     # expression(X["5,5"], X["4,5"], X["3,5"], X["2,5"], X["1,5"])