[R] create variables with indexes

Erik Iverson eriki at ccbr.umn.edu
Wed Jul 14 02:41:29 CEST 2010


> Suppose I want create variables with indexes in their names, e.g., X_1_1,
> X_1_2, X_1_3, ..., X_1_10,  X_2_1, X_2_2, X_2_3, .. X_2_10,..., X_10_1,
> X_10_2, ... X_10_10. It looks like I need to use 2 indexes I and J so I is
> looped from 1 to 10, and J is looped from 1 to 10. But I don't know how to
> automatically produce X with these combination of indexes. Should I use paste
> function? Can someone help?

In the long run, there's probably a better way to do what you want than creating 
all these variables, such as storing all your data in an appropriate structure 
such as a vector, matrix, list, or data.frame.

All I can guess from your post that you want is to create a character vector of 
the strings you mention, in which case:

outer(1:10, 1:10, function(x, y) paste("X", x, y,sep = "_"))

will help.


To see what I'm talking about in the first paragraph, see the difference between.



X_1_1 <- 1
X_1_2 <- 2
X_2_1 <- 3
X_2_2 <- 4

vs.

X <- matrix(1:4, ncol = 2)

and then indexing using the usual style.

X[1,2]
X[1,]
X[,1]

etc...



More information about the R-help mailing list