Reputation: 789
I have a datatable as shown below
Event Time
0 0
0 0
0 0
0 0
1 1
0 7
0 11
1 20
0 21
Here, 1 indicates Event = Yes, 0 is Event= No. What I am trying to do is tranform this raw dataset into four columns, time, SampleSize, Event, Non-Event.
time SampleSize Event Non-Event
0 9 0 4
1 5 1 0
7 4 0 1
11 3 0 1
20 2 1 0
21 1 0 1
Not sure how to go about doing this. Any help on accomplishing this is much appreciated.
Upvotes: 0
Views: 137
Reputation: 3184
Please my answer using base R:
# raw data
d1 <- data.frame(Event = c(0,0,0,0,1,0,0,1,0),
Time = c(0,0,0,0,1,7,11,20,21))
d2 <- as.data.frame.matrix(table(d1$Time, d1$Event))
colnames(d2) <- c("Non-Event", "Event")
times <- as.numeric(rownames(d2))
d3 <- cbind(time = times,
SampleSize = sapply(times, function(x){
nrow(d1) - min(which(x == d1$Time)) + 1
}),
d2)
rownames(d3) <- NULL
d3
# time SampleSize Non-Event Event
#1 0 9 4 0
#2 1 5 0 1
#3 7 4 1 0
#4 11 3 1 0
#5 20 2 0 1
#6 21 1 1 0
Upvotes: 1