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?

3
  • 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 Commented Mar 26, 2019 at 16:07
  • 2
    How do I make a list of data frames? related/possible dupe. Commented Mar 26, 2019 at 16:24
  • 3
    Possible duplicate of How do I make a list of data frames? Commented Mar 26, 2019 at 17:21

1 Answer 1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.