Warm tip: This article is reproduced from stackoverflow.com, please click
list r

Convert elements of list to dataframe keeping column names unchanged

发布于 2020-03-27 10:31:48

I have a list with several elements in it. I want to convert these elements to separated dataframes. However, I dont know how to retain column names. Please see the code below.

for (i in 1: length(mylist)) {
 assign(paste("df_",names(mylist[i]),sep = ""), as.data.frame(data.frame(mylist[i]),
col.names = names(dfi)))
}
names(df_april)

> names(df_april)
[1] "april.X"              "april.Latitude"       "april.month"          "april.count1"         "april.AOT40_1"        "april.count_full"    
[7] "april.AOT40_2"        "april.State.Code"     "april.County.Code"    "april.Longitude"      "april.Datum"          "april.Parameter.Name"
[13] "april.State.Name"     "april.County.Name"    "april.year"           "april.method"

As you can see above, I tried to use as.data.frame with defined col.names = names(dfi) to get rid of "april" in those column names. But it did not work.

Any idea?

Questioner
Yabin Da
Viewed
79
akrun 2019-07-04 00:25

In the OP's code, change the [ to [[ as the first is still a list of length 1 and have a list name as well, while the second [[ extracts the list element. So, naturally, when we do the as.data.frame, the list element names also gets appended while flattening that element

for (i in seq_along(mylist)) {
    assign(paste("df_",names(mylist[[i]]),sep = ""), mylist[[i]],
         col.names = names(dfi)))
  }
names(df_april)

NOTE: It is better not to create mutiple objects in the global env.