0

I have a for loop as

for(i in c("a","b","c","d"))
{
    as.name(paste("df",i,sep=""))= mydataframe
}

mydataframe is a data frame and I want to create data frames dfa,dfb,dfc and dfd using this loop.

The as.name(paste("df",i,sep="")) does not work here. I do not want to create a list that has the 4 data frames.

Can I directly create 4 data frames from this loop?

RN92
  • 1,380
  • 1
  • 13
  • 32
sparkstars
  • 87
  • 7
  • 1
    This is a bad design pattern in R. It's better to work with a [list of data.frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames). You can much more easily work with data in a list rather than creating a bunch of similarly named variables in your global environment. – MrFlick Mar 12 '19 at 02:43
  • Possible duplicate: https://stackoverflow.com/questions/7914568/r-create-variables-in-loop – MrFlick Mar 12 '19 at 02:43
  • Another possible duplicate: https://stackoverflow.com/questions/16566799/change-variable-name-in-for-loop-using-r – MrFlick Mar 12 '19 at 02:45

1 Answers1

1

You can do this using assign. Although in general, you are better off using lists.

Using your example:

for(i in letters[1:4]){
  assign(paste0("df", i), mydataframe)
}

Note that this will simply create the same object 4 times, unless you change what mydataframe is inside the loop.

Frans Rodenburg
  • 476
  • 6
  • 17