-1

I have used 'assign' to create a number of variables and assigned to them values:

N <- 10
for(i in 1:N)
{
    #create variable names n1, ..., n'N'
    assign(paste0("name",i), data.frame(matrix(1:100, ncol=3, nrow=100)))
}

I now need to be able to access these variable names, but NOT assign anything to them; I need to just change their column headers (in this application). The following code doesn't work, but something like this:

for(i in 1:N)
{
    #create proper column headers
    colnames(assign(paste0("name",i), ???) <- c("a","b","c")
}

I would like to know what to put in place of "???" or to learn of a different approach.

There are other applications that would also not involve assigning anything to the variables.

bill999
  • 2,147
  • 8
  • 51
  • 103
  • Once you have a variable named `foo`, just do `colnames(foo)<-c('firstname','secondname')` – Carl Witthoft Dec 20 '13 at 22:36
  • But how do I write 'foo' in a loop setting like I have? I mean 'foo1', 'foo2', 'foo3', etc. I have to append the number to 'foo' somehow. This is the problem. If I just do 'paste0("foo",i)', then this is a string and not a variable name. – bill999 Dec 20 '13 at 22:38
  • 1
    you use `get('foo1')`. However, the more `R`-ish way is to use a named list rather than `assign`: `for(...) {yourlist[[i]] <- ...}`. – Justin Dec 20 '13 at 22:40
  • 1
    Related: http://stackoverflow.com/q/2679193/271616 – Joshua Ulrich Dec 22 '13 at 14:58

1 Answers1

2

You could do something like mynames<-ls("name") to get a collection of names and muck with that, but if this is the way you're going, better either to assign the colnames at the same time you create the data.frames by using structure, or much simpler: create a list variable with N elements and assign names to the list elements (and assign the dataframes to the list elements as well).

`my.list`<-list()
for (i in 1:N) {
       my.list[[i]]<-data.frame(matrix(1:100, ncol=3, nrow=100))
       names(my.list)[i]<-paste('name',i)
}
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73