-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.

4
  • Once you have a variable named foo, just do colnames(foo)<-c('firstname','secondname') Commented Dec 20, 2013 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. Commented Dec 20, 2013 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]] <- ...}. Commented Dec 20, 2013 at 22:40
  • 1
    Related: stackoverflow.com/q/2679193/271616 Commented Dec 22, 2013 at 14:58

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.