Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `map()` in nested data frame

I am having some problems using the map() function along with the nest() function.

I have some data set up like the following:

counter

    counter           date_time total
1  06032013 2013-06-03 16:00:00   476
2  06032013 2013-06-03 17:00:00   578
3  06032013 2013-06-03 18:00:00   406
4  06032013 2013-06-03 19:00:00   272
5  06032013 2013-06-03 20:00:00   240
6  06032013 2013-06-03 21:00:00    96
7  06032013 2013-06-03 22:00:00    67
8  06032013 2013-06-03 23:00:00    37
9  06032013 2013-06-04 00:00:00    10
10 06032013 2013-06-04 01:00:00    11
11 06032013 2013-06-04 02:00:00     8
12 06032013 2013-06-04 03:00:00     9
13 06032013 2013-06-04 04:00:00    23
14 06032013 2013-06-04 05:00:00    83
15 06032013 2013-06-04 06:00:00   291
16 06032013 2013-06-04 07:00:00   532
17 06032013 2013-06-04 08:00:00   434
18 06032013 2013-06-04 09:00:00   326
19 06032013 2013-06-04 10:00:00   310
20 06032013 2013-06-04 11:00:00   292

I then nested these data based on the counter field. Such as:

y <- counters %>% nest(-counter)

y 

# A tibble: 140 × 2
    counter               data
      <chr>             <list>
1  06032013  <tibble [91 × 2]>
2  62295051 <tibble [310 × 2]>
3  81295014 <tibble [301 × 2]>
4  81295015 <tibble [294 × 2]>
5  81295091 <tibble [303 × 2]>
6  81295092 <tibble [306 × 2]>
7  81313062 <tibble [142 × 2]>
8  81313063 <tibble [142 × 2]>
9  82295046 <tibble [139 × 2]>
10 82295050 <tibble [141 × 2]>

What I want to do is map over each nested data frame and construct an xts matrix in my nested data frame. I tried many variations of the following code:

y %>% mutate(stuff = map(xts(data$total, order.by = data$date_time)))

I am greeted with Error in data$date_time : object of type 'closure' is not subsettable.

Any thoughts would be great!

like image 682
thus__ Avatar asked Dec 20 '16 03:12

thus__


1 Answers

@Michael-Griffiths thank you for your help! The following code worked for me:

y %>% mutate(stuff = map(data, ~xts(order.by = .x$date_time)))

# A tibble: 140 × 3
    counter               data     stuff
     <fctr>             <list>    <list>
1  06032013  <tibble [91 × 2]> <S3: xts>
2  62295051 <tibble [310 × 2]> <S3: xts>
3  81295014 <tibble [301 × 2]> <S3: xts>
4  81295015 <tibble [294 × 2]> <S3: xts>
5  81295091 <tibble [303 × 2]> <S3: xts>
6  81295092 <tibble [306 × 2]> <S3: xts>
7  81313062 <tibble [142 × 2]> <S3: xts>
8  81313063 <tibble [142 × 2]> <S3: xts>
9  82295046 <tibble [139 × 2]> <S3: xts>
10 82295050 <tibble [141 × 2]> <S3: xts>
# ... with 130 more rows

Still not 100% sure as to why. But hey, it worked.

like image 68
thus__ Avatar answered Nov 13 '22 15:11

thus__