Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use <code>reshape()</code> for the first step, but then you need to do some more work. Also, <code>reshape()</code> needs a <code>data.frame()</code> as its input, but your sample data is a matrix.</p> <p>Here's how to proceed:</p> <ol> <li><p><code>reshape()</code> your data from wide to long:</p> <pre><code>dat2 &lt;- reshape(data.frame(dat), direction = "long", idvar = c("id", "cohort"), varying = 3:ncol(dat), sep = "") dat2 # id cohort time s dur # 1.1.1 1 1 1 3 4 # 2.0.1 2 0 1 1 4 # 1.1.2 1 1 2 2 5 # 2.0.2 2 0 2 4 3 </code></pre></li> <li><p>"Expand" the resulting <code>data.frame</code> using <code>rep()</code></p> <pre><code>dat3 &lt;- dat2[rep(seq_len(nrow(dat2)), dat2$dur), c("id", "cohort", "s")] dat3[order(dat3$id), ] # id cohort s # 1.1.1 1 1 3 # 1.1.1.1 1 1 3 # 1.1.1.2 1 1 3 # 1.1.1.3 1 1 3 # 1.1.2 1 1 2 # 1.1.2.1 1 1 2 # 1.1.2.2 1 1 2 # 1.1.2.3 1 1 2 # 1.1.2.4 1 1 2 # 2.0.1 2 0 1 # 2.0.1.1 2 0 1 # 2.0.1.2 2 0 1 # 2.0.1.3 2 0 1 # 2.0.2 2 0 4 # 2.0.2.1 2 0 4 # 2.0.2.2 2 0 4 </code></pre></li> </ol> <p>You can get rid of the funky row names too by using <code>rownames(dat3) &lt;- NULL</code>.</p> <h2>Update: Retaining the ability to revert to the original form</h2> <p>In the example above, since we dropped the "time" and "dur" variables, it isn't possible to directly revert to the original dataset. If you feel this is something you would need to do, I suggest keeping those columns in and creating another <code>data.frame</code> with the subset of the columns that you need if required.</p> <p>Here's how:</p> <p>Use <code>aggregate()</code> to get back to "dat2":</p> <pre><code>aggregate(cbind(s, dur) ~ ., dat3, unique) # id cohort time s dur # 1 2 0 1 1 4 # 2 1 1 1 3 4 # 3 2 0 2 4 3 # 4 1 1 2 2 5 </code></pre> <p>Wrap <code>reshape()</code> around that to get back to "dat1". Here, in one step:</p> <pre><code>reshape(aggregate(cbind(s, dur) ~ ., dat3, unique), direction = "wide", idvar = c("id", "cohort")) # id cohort s.1 dur.1 s.2 dur.2 # 1 2 0 1 4 4 3 # 2 1 1 3 4 2 5 </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