Dr.ew
Dr.ew

Reputation: 11

Sequentially naming variables (beginner)

I would like to assign data created within a loop to a corresponding series of sequentially- numbered variables. As written, the loop in this example simply overwrites each time, so that all is stored is the final dataset assigned to matrix stooges. What I would like to do is to have each iteration create a new variable, called “somename(counter)”, and store the current values for matrix stooges in that variable. The loop below, then, should create variables somename0, with values 0,0,0,0, somename1, with values 1:4, and somename2 with values 2,4,6,8. I think creating the variables dynamically within the loop is best in order to automate the naming of the variables and how many are created.

ex:

no_its <- 3  
counter <- 0
while(counter < no_its){
    a <- c(counter*(1:4))
    stooges <- as.matrix(a)
    rownames(stooges)<-c("Larry","Moe","Curly","Shemp")
    counter <- counter+1
}
stooges

output:
      [,1]
Larry    2
Moe      4
Curly    6
Shemp    8

Upvotes: 1

Views: 2203

Answers (2)

IRTFM
IRTFM

Reputation: 263451

If you want a matrix, then create an empty matrix and then populate it:

 stooges <- matrix(NA, ncol=4, nrow=4)
 row.names(stooges)<-c("Larry","Moe","Curly","Shemp")
 stooges[1:4, 1:4] <- col(stooges) * 1:4
 stooges
#---------
      [,1] [,2] [,3] [,4]
Larry    1    2    3    4
Moe      2    4    6    8
Curly    3    6    9   12
Shemp    4    8   12   16

Upvotes: 0

baptiste
baptiste

Reputation: 77116

Try using lists, it will always prove a better choice in R

counter <- 0:2
names(counter) <- paste("somename",seq_along(counter)-1,sep="")
(result <- lapply(counter, function(counter) counter*1:4))
result[["somename1"]]
## only if you must
attach(result, pos=2)
ls(pos=2)

Upvotes: 2

Related Questions