0

I am interested in something like this:

for (i in 1:10) {
    df[i]<-function(x,y,i)
}

Where I would like the output to be 10 different dataframes with names df1, df2, df3, etc.

I know you can include variables in a dataframe column name using:

for (i in 1:10) {
    df[,paste0(i)]<-function(x,y,i)
}

But I would like 10 separate dataframes, not 1 dataframe with 10 appropriately named columns.

Anna
  • 825
  • 1
  • 11
  • 19
  • 3
    Generally having a bunch of different variables lying around in the global namespace with similar names and data structures just makes things more difficult later to work with them. In the long run you'll probably be happier keeping such related items in a named list and just use `lapply()` or `Map()` to create that list. This is a much more R-like way to work with data. Better to [avoid assign()](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). – MrFlick Aug 24 '17 at 14:43

1 Answers1

2

You can use assign. Here, I create 10 vectors called df1, df2, etc., and assign them values from a function (e.g., sqrt).

for (i in 1:10) {
  assign(paste("df", i, sep = ""), sqrt(i))
}

Edit

If you want to create a data frame with a column that has a dynamic name, you could use this:

for (i in 1:10) {
  assign(paste("df", i, sep = ""), setNames(data.frame(1:5), LETTERS[i]))
}

Here, I used LETTERS to name my columns, but you can use whatever you like.

Dan
  • 11,370
  • 4
  • 43
  • 68
  • Thanks @Lyngbakr! What if I wanted to assign my function output to a specific column within the dataframe? Ex. `assign(paste("df", i, sep = "")[[InfoTable$Name[i]]], sqrt(i))` The syntax isn't quite right but I'm not sure where to use either the [[]] or the $ operator – Anna Aug 24 '17 at 14:53
  • Like this? `assign(paste("df", i, sep = ""), data.frame(Stuff = 1:5))` This adds it to a column named `Stuff`. – Dan Aug 24 '17 at 15:41