Home > other >  Extract single value from function that returns multiple values for use with dplyr() pipe
Extract single value from function that returns multiple values for use with dplyr() pipe

Time:05-07

I have the following data:

date_range <- c('2020-01-31',
           '2020-02-28',
           '2020-03-31',
           '2020-04-30',
           '2020-05-31',
           '2020-06-30',
           '2020-07-31',
           '2020-08-31',
           '2020-09-30',
           '2020-10-31',
           '2020-11-30',
           '2020-12-31',
           '2021-01-31',
           '2021-02-28',
           '2021-03-31',
           '2021-04-30',
           '2021-05-31',
           '2021-06-30',
           '2021-07-31',
           '2021-08-31',
           '2021-09-30',
           '2021-10-31',
           '2021-11-30',
           '2021-12-31'
           )

date_range <- as.Date(date_range)

returns <- c(0.134,
                    0.007,
                   -0.036,
                    0.112,
                    0.001,
                   -0.033,
                    0.344,
                    0.020,
                   -0.046,
                    0.123,
                    0.309,
                    0.223,
                    0.100,
                    0.239,
                   -0.009,
                    0.055,
                    0.029,
                   -0.104,
                    0.074,
                    0.172,
                   -0.098,
                    0.180,
                   -0.022,
                   -0.072
                    )

Now, I use the following to get the maximum drawdown:

library(ts)
maxdrawdown(returns)

This gives:

[1] 0.448

$from
[1] 7

$to
[1] 18

I extract the first value of the return set with:

maxdrawdown(returns)[1]

This gives:

> maxdrawdown(returns)[1]
$maxdrawdown
[1] 0.448

Using dplyr, I would like to aggregate by year. So, I do the following:

df %>%
  group_by(year(dates)) %>%
  summarize(max_dd = maxdrawdown(returns)[1]
  ) 

But, this returns no values:

# A tibble: 2 x 2
  `year(dates)` max_dd      
          <dbl> <named list>
1          2020 <dbl [1]>   
2          2021 <dbl [1]> 

Is this something wrong with my syntax?

Thanks!

CodePudding user response:

can you try [[1]] (which will return a number) instead of [1] (which will return a list)?

  • Related