I have 28 list within a list and I try to add another variable called ID to each individual list. I found this Dataframes in a list; adding a new variable with name of dataframe to be very helpful. But when i tried his code, it doesn’t work in my case. I think it’s because my list doesn’t have clear labels [1],[2].[3], etc.. that the code can recognize.
all$id <- rep(names(mylist), sapply(mylist, nrow))
>List of 1
$ :List of 28
..$ :'data.frame': 271 obs. of 12 variables:
.. ..$ Sample_ID : Factor w/ 271 levels "MC25",..: 19 27 2
.. ..$ Reported_Analyte : Factor w/ 10 levels "2-Butoxyethanol",..: 7 7 7
..$ Date_Collected : Factor w/ 71 levels "2010-05-08","2010-05-09",..: 8 9 1
.. ..$ Result2 : num [1:271] 0.11 0.11 0.11 0.11
..$ :'data.frame': 6 obs. of 12 variables:
.. ..$ Sample_ID : Factor w/ 271 levels "MC25",..: 19 27 2
.. ..$ Reported_Analyte : Factor w/ 10 levels "2-Butoxyethanol",..: 7 7 7
..$ Date_Collected : Factor w/ 71 levels "2010-05-08","2010-05-09",..: 8 9 1
.. ..$ Result2 : num [1:271] 0.11 0.11 0.11 0.11
It really isn’t very clear what you want to achieve (the post you linked to was about collapsing over the list of data frames and adding into the collapsed version an ID variable indicating which original data frame each row in the collapsed data frame came from).
I see a complication with your data; you have a list of 28 data frames within a list. You can see that in the output from
str()that is given in your Q. You can see this better with this example data set (here all the data frames are the same but that is just for expedience)If we look at
mylistusingstr()we see the nature of the complication I mentioned:Where the post you linked to was starting from was the list inside your outer list and that list had named components. If you don’t need the outer list, perhaps best to throw it away at this stage:
Names can then be added to this list
which would result in
Notice the
List of 1is no longer reported.If the list of data frames within a list is important to you (not sure why it would be, but OK), then you can assign the names to the
[[1]]st component directly.(Notice I’m using the original
mylistand on both occasions I index that list with[[1]].)The result is similar to the above though the list within a list structure is retained:
If you now wish to proceed with collapsing the individual data frames into a single data frame, but retaining the information about which data frame they came from, we would do this for
mylist2:which gives:
For
mylistwe use something very similar, but just index intomylistusing[[1]]:As you can see repeatedly having to refer to your list of data frames as
mylist[[1]]is a pain if you dont need the outer list.Update:
If you don’t want to collapse the list into a single data frame, see @Andrie’s answer, but modify it to read:
so you account for the list within list structure.