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?
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.
Problem still there. The question is after I convert the element to a dataframe, how should I retain names in dataframe? I am not trying to name the elements in the list.
The thing is I need to do some manipulation after I convert list elements to dataframes. Those manipulation cannot be done on list element like
mylist2[[1]]
.That's amazing. Thanks a ton. I just realized the difference between
mylist[1]
andmylist[[1]]
.