0
votes

Let I have a list(list1) which consists data frames(df1,df2,..,dfn):

Each data frame consist different number of columns. As an example

list1[[1]]=df1

where df1:

x       y
----   -----
45     6
65     87
12     90

and

list1[[2]]=df2

where df2:

a       b      c
----   ----    ----
23     67      43
71     13      8
2      9       12

I want to unlist list1 as returns df1 and df2

df1:

a1     a2
----   -----
45     6
65     87
12     90

df2:

b1     b2      b3
----   ----    ----
23     67      43
71     13      8
2      9       12

Namely,

  • first data frame(df1) will headers as a1,a2,a3.....

  • second data frame(df2) will headers as b1,b2,b3.....

  • third data frame(df3) will headers as c1,c2,c3.....

and goes on.

How can I do that in R? I will be very glad for any help. Thanks a lot.

3
Why do you not want to keep them in a list? Look at list2env and setNames for what it sounds like you're asking for.A5C1D2H2I1M1N2O1R2T1
@A Handcart And Mohair, Since I will export each data frame as excel file, I want to unlist them.oercim
You can use lapply instead of creating a lot of objects in your workspace. Anyway, list2env will do what you are calling an "unlist" activity.A5C1D2H2I1M1N2O1R2T1
As you told, I can use lapply for exporting the elements of list. However I can't rename the column names.oercim
Sure you can. That's why I suggested setNames.A5C1D2H2I1M1N2O1R2T1

3 Answers

3
votes

Here's a mockup of what I was describing in the comments. I'm not showing list2env because that seems unnecessary to your end goal.

Sample data:

myList <- replicate(10, data.frame(v1 = 1:2, v2 = 3:4), FALSE)

Renaming columns and writing the data to csv files:

lapply(seq_along(myList), function(x) {
  FileName <- sprintf("%s.csv", letters[x])
  write.csv(setNames(myList[[x]], paste0(letters[x], 1:length(myList[[x]]))), 
            file = FileName, row.names = FALSE)
})

The result would be 10 csv files, named a.csv, b.csv, and so on, wherein a.csv will have columns named "a1" ... "an".

3
votes

Here's how you can rename columns for data frames in a list using a loop.

for (i in seq_along(list1)) {
    setNames(list1[[i]], paste0(letters[i], seq_along(list1[[i]])))
}
2
votes

Thanks a lot @A Handcraft And Mohair and @Gregor for your time. With suggestions of @A Handcraft And Mohair, my code is as below:

list2<-list()
for(i in seq_along(list1))
  {
list2[[i]]<-setNames(list1[[i]], paste(letters[[i]],1:ncol(list1[[i]])))
}