0

I am trying to use for loop in R to create separate data frames for my split result. It may have better solutions but I am a beginner in R so any comments are appreciated.

''' For example: '''

For (i in 1:100)
{i<-df[[i]]}

''' I expect to get something like

'1' equal to df[[1]]
'2' equal to df[[2]]
'3' equal to df[[3]]
.
.
.
'i' equal to df[[i]]

but it only gets the last i:

'100' which is equal to  df[[100]]

How can I get separate data frames for each i?

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Nancy
  • 1
  • 1
    you are trying to create 100 objects in the environment. INstead just keep the list as such or data.frame .and process whenever needed – akrun Mar 26 '19 at 16:07
  • 2
    [How do I make a list of data frames?](https://stackoverflow.com/a/24376207/903061) related/possible dupe. – Gregor Thomas Mar 26 '19 at 16:24
  • 3
    Possible duplicate of [How do I make a list of data frames?](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) – Hector Haffenden Mar 26 '19 at 17:21

1 Answers1

1

Since you require individual data frames, you can use the following to create a list of data frames:

df = NULL
for (i in 1:100) {
  df[[i]] = data.frame(i)
}

You can access each data frame in the list using the list index. For exampe

> df[[1]]
  i
1 1
> df[[2]]
  i
1 2

You can verify that each item in the list is a data frame

> str(df) # Partial output given
List of 100
 $ :'data.frame':   1 obs. of  1 variable:
  ..$ i: int 1
 $ :'data.frame':   1 obs. of  1 variable:
  ..$ i: int 2
 $ :'data.frame':   1 obs. of  1 variable:
  ..$ i: int 3
 $ :'data.frame':   1 obs. of  1 variable:
  ..$ i: int 4
.
.
.

Once you are more comfortable with R, a better way to achieve this result is to vectorize the task, such as by using lapply

df = lapply(1:100, data.frame)
NM_
  • 1,887
  • 3
  • 12
  • 27