Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a way using negative values for <code>head</code> and <code>tail</code>:</p> <pre><code>SPX &lt;- getSymbols("^GSPC", src="yahoo", auto.assign=FALSE) do.call(rbind, lapply(split(SPX, 'months'), function(x) tail(head(x, -2), -9))) </code></pre> <p>It splits by "months", then applies a function to each month. The function gets all but the first 9 days of all but the last 2 days in the <code>xts</code>. Finally, <code>rbind</code> the results together into a single <code>xts</code> object.</p> <p><strong>Edit:</strong></p> <p>You can use <code>xts::first</code> and <code>xts::last</code> instead of <code>head</code> and <code>tail</code> so that it will work with frequencies other than daily.</p> <pre><code>do.call(rbind, lapply(split(SPX, 'months'), function(x) { first(xts::last(x, "-2 days"), "-9 days") })) </code></pre> <p><strong>Update to address comment:</strong></p> <p>If you want to do other operations on the subsets, you need to check to make sure there's at least 1 row of data. If, for a given month, there are no days in your xts object after the 9th and before the 2nd to last day, the anonymous function above will return <code>NULL</code>.</p> <pre><code>do.call(rbind, lapply(split(SPX, 'months'), function(x) { dat &lt;- first(xts::last(x, "-2 days"), "-9 days") if (NROW(dat) &gt; 0) OpCl(dat) })) </code></pre> <p>Although, in this case, you can just call <code>OpCl()</code> on the results of my original answer to get the same result.</p> <pre><code>tmp &lt;- do.call(rbind, lapply(split(SPX, 'months'), function(x) { first(xts::last(x, "-2 days"), "-9 days") })) OpCl(tmp) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload