Finding ratio of positive to total case in each quarter using "table" function

Viewed 31

I have a data set with two important columns that are shown below (sample rows are shown below):

sub_select <- structure(list(yq = c("2014 Q4", "2014 Q3", "2014 Q4", "2014 Q3", 
"2014 Q4", "2014 Q3", "2014 Q4", "2014 Q3", "2014 Q4", "2014 Q2"
), result = c(FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, 
TRUE, FALSE)), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10"))

   yq        result
      
 1 2014 Q4   FALSE    
 2 2014 Q3   TRUE    
 3 2014 Q4   FALSE    
 4 2014 Q3   TRUE    
 5 2014 Q4   FALSE    
 6 2014 Q3   FALSE    
 7 2014 Q4   TRUE    
 8 2014 Q3   FALSE    
 9 2014 Q4   TRUE    
10 2014 Q2   FALSE 
     ...      ...
     ...      ...
     ...      ...

what I want to do is to create a column for each year quarter which has the ratio of "TRUE" to the total case. To do this, I used the "table" function as shown below:

 table(sub_select$yq, sub_select$result)

the result is in this form:

          FALSE TRUE
  2014 Q4   880   46
  2015 Q1  1815   77
  2015 Q2  1677   73
  2015 Q3  1191   50
  2015 Q4   555   13

However, what I want to do is having a ratio of the "TRUE" case to the total number of cases. So, basically, a column which includes 46/(46+880) , etc ... how can I do that?

Thanks

1 Answers

We can use prop.table

out <- table(sub_select$yq, sub_select$result)
cbind(out, prop = prop.table(out, 1)[,2])

Or another option is divide by the rowSums and cbind that as new column

out <- table(sub_select$yq, sub_select$result)
cbind(out, prop = out[,2]/rowSums(out))

-output

#        FALSE TRUE prop
#2014 Q2     1    0  0.0
#2014 Q3     2    2  0.5
#2014 Q4     3    2  0.4

data

sub_select <- structure(list(yq = c("2014 Q4", "2014 Q3", "2014 Q4", "2014 Q3", 
"2014 Q4", "2014 Q3", "2014 Q4", "2014 Q3", "2014 Q4", "2014 Q2"
), result = c(FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, 
TRUE, FALSE)), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10"))
Related