user1638567
user1638567

Reputation: 79

Use loop to split a list into multiple dataframes

I am a beginner in R and I have not been able to find a solution to this anywhere online.

I have a list object that is composed of 50 dataframes. I want to split this list into separate data.frame objects, but am having trouble doing this.

It's simple to do manually:

a<-list[[1]]

but I want to loop it so that I don't have to manually enter all 50 components. This does not work:

for(i in 1:n.imp)
    a.i<-comb.txt1[[i]]

because it only produces a single (the last) dataframe.

Any thoughts?

Here is some additional context: This list is the product of a multiple imputation procedure -- mi(). I want to merge a new variable into each of these imputed datasets, but can't seem to figure out how to do that, since the object is a list.

Upvotes: 2

Views: 6163

Answers (3)

Matthew Plourde
Matthew Plourde

Reputation: 44634

You can use attach(comb.txt1), if your list has names or you give it names with something like names(comb.txt1) <- paste('a', seq_along(comb.txt1), sep='.')

Cluttering your workspace with 50 data.frames probably isn't necessary, though. Say the new variable you want to add to each data.frame is some atomic vector var (ie, a vector like c(1,2,3)). You could add it to each data.frame in your list with lapply(comb.txt1, function(comb.txt1.DF) within(comb.txt1.DF, new.var <- var)).

Upvotes: 2

ptocquin
ptocquin

Reputation: 325

I am not sure that is what your are looking for, but ...

Producing a list of data frames :

> set.seed(1)
> df1 <- data.frame(a=rnorm(10), b=rnorm(10))
> df2 <- data.frame(a=rnorm(10), b=rnorm(10))
> df3 <- data.frame(a=rnorm(10), b=rnorm(10))

> my.list <- list(df1, df2, df3)

Then, using assign() with lapply() :

> lapply(seq_along(my.list), 
         function(i,x) {assign(paste0("a",i),x[[i]], envir=.GlobalEnv)},
         x=my.list)

> a1
            a           b
1  -0.6264538  1.51178117
2   0.1836433  0.38984324
3  -0.8356286 -0.62124058
4   1.5952808 -2.21469989
5   0.3295078  1.12493092
6  -0.8204684 -0.04493361
7   0.4874291 -0.01619026
8   0.7383247  0.94383621
9   0.5757814  0.82122120
10 -0.3053884  0.59390132

Upvotes: 1

seancarmody
seancarmody

Reputation: 6290

I think this is what you are after:

for(i in 1:length(comb.txt1)) {
    assign(paste0("a.", i), comb.txt1[[i]])
}

Upvotes: 4

Related Questions