user1757436
user1757436

Reputation: 151

R How to reshape matrix using value in a column

I have matrix like this:

ID     Count
1      2
2      3
3      2

I want to create a matrix in which the number of rows for an ID equals the value of Count while adding a new column containing the index for each row within the ID value. For the matrix above, the result should be:

ID   Index
1    1
1    2
2    1
2    2
2    3
3    1
3    2

Upvotes: 1

Views: 49

Answers (2)

CPak
CPak

Reputation: 13591

Using tidyverse

library(tidyverse)
df1 <- df %>% 
          group_by(ID) %>% 
          nest() %>% 
          mutate(data=map(data,~seq_along(1:.x$Count))) %>% 
          unnest(data)

Output

     ID  data
1     1     1
2     1     2
3     2     1
4     2     2
5     2     3
6     3     1
7     3     2

Upvotes: 1

Neal Fultz
Neal Fultz

Reputation: 9696

For a simple case you can just use rep and sequence.

ID=c(1,2,3)
Count=c(2,3,2)
cbind(ID=rep(ID, Count), Index=sequence(Count))
#     ID Index
#[1,]  1     1
#[2,]  1     2
#[3,]  2     1
#[4,]  2     2
#[5,]  2     3
#[6,]  3     1
#[7,]  3     2

Upvotes: 3

Related Questions