1

Following on from a question I asked previously, I want to know if it is possible to extract and/or group list elements based on the elements' names.

All of the list elements contain hourly data over several days (spanning several months) and follow the same naming structure of:

YYYY-MM-DD HH

Here is what my list looks like (note that there are data for other months too, hence why I want to specifically target individual months):

enter image description here

What I want to do is to extract every list element with the same MM value and then save the combined list as a data frame.

In this example, I want everything from January to be grouped together in a data frame, and for this to be repeated for the other months of the year.

The idea is that I end up with 12 data frames each representing a month of the year.

How can this be achieved?

Mus
  • 7,290
  • 24
  • 86
  • 130

1 Answers1

1

You could try the following:

my_list = list('YYYY-01-DD HH-MM-SS' = data.frame(id=1),
                       'YYYY-01-DD HH-MM-SS' = data.frame(id=2),
                       'YYYY-02-DD HH-MM-SS' = data.frame(id=3),
                       'YYYY-01-DD HH-MM-SS' = data.frame(id=4))

library(data.table)
lapply(split(my_list,substr(names(my_list),6,7)),rbindlist)

which outputs:

$`01`
   id
1:  1
2:  2
3:  4

$`02`
   id
1:  3

Hope this helps!

Florian
  • 24,425
  • 4
  • 49
  • 80
  • Thank you, this is great but it isn't quite what I wanted as my input is a list object and not a data frame object. Ultimately I want the output to be a data frame object which has been created via the list. I will update the question and provide some more detail to make things a little clearer. – Mus Apr 05 '18 at 12:29
  • I modified my answer, I hope this better suits what you were expecting :) – Florian Apr 05 '18 at 12:33
  • Thanks @Florian, but I seem to get a different result when I save the output to `january`. What it resulted in was a single list object with every month's data compacted into it. What am I doing wrong? – Mus Apr 05 '18 at 12:42
  • Alright, I think I get it now ;) Please let me know if this works for you! If not, please consider adding a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), that would help a lot. – Florian Apr 05 '18 at 12:47
  • Perfect! Thank you for working through this with me, @Florian! For those following along, I created a `months` object, saved the output to that, and then I created `january`/`february` objects and saved the respective list elements to them (so `january <- months$'01'`, `february <- months$'02'` and so on). – Mus Apr 05 '18 at 12:52