Note that there are some explanatory texts on larger screens.

plurals
  1. POExpand ranges defined by "from" and "to" columns
    primarykey
    data
    text
    <p>I have a data frame containing <code>"name"</code> of U.S. Presidents, the years when they start and end in office, (<code>"from"</code> and <code>"to"</code> columns). Here is a sample:</p> <pre><code>name from to Bill Clinton 1993 2001 George W. Bush 2001 2009 Barack Obama 2009 2012 </code></pre> <p>...and the output from <code>dput</code>:</p> <pre><code>dput(tail(presidents, 3)) structure(list(name = c("Bill Clinton", "George W. Bush", "Barack Obama" ), from = c(1993, 2001, 2009), to = c(2001, 2009, 2012)), .Names = c("name", "from", "to"), row.names = 42:44, class = "data.frame") </code></pre> <p>I want to create data frame with two columns (<code>"name"</code> and <code>"year"</code>), with a row for each year that a president was in office. Thus, I need to create a regular sequence with each year from "<code>from</code>", to <code>"to"</code>. Here's my expected out:</p> <pre><code>name year Bill Clinton 1993 Bill Clinton 1994 ... Bill Clinton 2000 Bill Clinton 2001 George W. Bush 2001 George W. Bush 2002 ... George W. Bush 2008 George W. Bush 2009 Barack Obama 2009 Barack Obama 2010 Barack Obama 2011 Barack Obama 2012 </code></pre> <p>I know that I can use <code>data.frame(name = "Bill Clinton", year = seq(1993, 2001))</code> to expand things for a single president, but I can't figure out how to iterate for each president.</p> <p>How do I do this? I feel that I should know this, but I'm drawing a blank.</p> <h2>Update 1</h2> <p>OK, I've tried both solutions, and I'm getting an error:</p> <pre><code>foo&lt;-structure(list(name = c("Grover Cleveland", "Benjamin Harrison", "Grover Cleveland"), from = c(1885, 1889, 1893), to = c(1889, 1893, 1897)), .Names = c("name", "from", "to"), row.names = 22:24, class = "data.frame") ddply(foo, "name", summarise, year = seq(from, to)) Error in seq.default(from, to) : 'from' must be of length 1 </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. 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