user3372033
user3372033

Reputation: 31

Obtain an array (or a labeled vector) from a frequency table in R

I have a frequency table as follows:

group    time    event
a         1       0
a         2       1
a         3       0
a         4       2  
a         5       0
b         1       1
b         2       0
b         3       2
b         4       1
b         5       0

and I would like to obtain a table that represents only the times where the event was observed and linked to the group... something like this:

group   time (n times, depending how many events occurred for each time)
a       2
a       4
a       4 
b       1
b       3
b       3
b       4 

I have only obtained a vector with the "rep" function, but I loose the label of the group. As my original data contains thousands of rows, I really need a quick way to do the job in R. I really appreciate your suggestions!

Upvotes: 3

Views: 149

Answers (1)

codeola
codeola

Reputation: 838

Given your data

x <- data.frame(group=c(rep("a", 5), rep("b", 5)), 
                time=rep(1:5, 2), 
                event=c(0,1,0,2,0,1,0,2,1,0))

You want:

x[rep(seq_len(nrow(x)), x$event), 1:2]

Upvotes: 4

Related Questions