Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you can do this pretty easily using by(). Here's how I did it. I've put each block, along with an explanation below each block.</p> <pre><code>dividends &lt;- data.frame(barc_ln=c(0.26,NA,NA,NA,0.23,NA,0.85), barn_se=c(NA,0.56,NA,NA,0.28,NA,NA), bas_gy=c(NA,0.35,NA,0.40,NA,NA,0.15), bats_ln=c(NA,NA,NA,NA,NA,NA,NA), row.names=c("1999-01-01","1999-01-02","1999-01-03","2000-01-04","1999-01-05","2001-01-06","2001-01-07")) </code></pre> <p>This just creates the original data frame you gave.</p> <pre><code>dividends[,"dates"] &lt;- as.Date(row.names(dividends)) dividends &lt;- dividends[order(dividends[,"dates"]),] dividends[,"year"] &lt;- format(dividends$dates,"%Y") </code></pre> <p>This takes the row name dates, and then turns them into a new column ("dates") in the data frame. Then, we order the data frame (not necessarily required, but I find it to be more intuitive) by date and extract the year (as a character, mind you) using format.</p> <pre><code>div_output &lt;- data.frame(row.names=unique(dividends$year)) </code></pre> <p>Next, I create the output data frame that will receive the data. I use the unique() function on the year variable to get the unique vector of years. They're already ordered (one advantage of ordering the data frame).</p> <pre><code>for(x in 1:4) { div_output[,x] &lt;- by(dividends[,x],INDICES=dividends$year,FUN=sum,na.rm=TRUE) } names(div_output) &lt;- names(dividends)[1:4] </code></pre> <p>Using a simple loop, we just go through each of the columns and apply the by() function. The variable is the column, the indices are the year, and we just use the sum function. I tag on na.rm=TRUE so that instead of NAs, you get actual data.</p> <pre><code>print(div_output) barc_ln barn_se bas_gy bats_ln 1999 0.49 0.84 0.35 0 2000 0.00 0.00 0.40 0 2001 0.85 0.00 0.15 0 </code></pre> <p>And there's the output I get.</p>
 

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