rtidyversereshape

Spell Data to Long in R


I have spell data that includes an ID, a group indicator and the length of the spell.

> d <- data.frame(ID = 1:10, 
+            group = sample(c("a", "b"), 10, replace = T), 
+            spell_length = sample(1:3,10, replace = T))


> head(d)
  ID group spell_length
   1     b            1
   2     a            1
   3     a            3
   4     b            1
   5     a            1
   6     b            2

The goal is to reshape the data into a long format with 4 variables: ID, group, time (which runs from 1 to the spell_length) and indicator (0,1) whether the ID is still present in that spell (e.g., if the spell_length is 1, the ID should not be present in time 2 and 3).

ID group  time indicator
 1     b     1        1
 1     b     2        0
 1     b     3        0
 2     a     1        1
 2     a     2        0
 2     a     3        0
 3     a     1        1
 3     a     2        1
 3     a     3        1
 

Solution

  • Do you want reframe like below?

    d %>%
        reframe(time = 1:3, indicator = +(1:3 <= spell_length), .by = c(ID, group))
    

    such that

       ID group time indicator
    1   1     b    1         1
    2   1     b    2         0
    3   1     b    3         0
    4   2     a    1         1
    5   2     a    2         0
    6   2     a    3         0
    7   3     a    1         1
    8   3     a    2         1
    9   3     a    3         1
    10  4     b    1         1
    11  4     b    2         0
    12  4     b    3         0
    13  5     a    1         1
    14  5     a    2         0
    15  5     a    3         0
    16  6     b    1         1
    17  6     b    2         1
    18  6     b    3         0