I would like to understand how to get rid of all the loops I am using in this code. I have a dataframe of 20 rows. I am simply counting the number of occurrences that the variables rs and occ appear together. Here is the data:  d = structure(list(householdid.x = c(101366, 101366, 102481,                              102481, 103755, 103755, 103788, 103788, 103799, 103799,                              10422, 10422, 10429, 10429, 10433, 10433, 10499,                              10499, 105280, 105280), nhouse = c(4L, 4L, 4L, 4L, 4L,                                                                       4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L),            idno = c(1013661, 1013662, 1024812, 1024811, 1037552, 1037551,                     1037881, 1037882, 1037991, 1037992, 104222, 104221, 104291,                     104292, 104331, 104332, 104992, 104991, 1052802, 1052801),            rs = c(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,                   0, 0, 1), occ = c(0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0,                                     0, 0, 0, 0, 0, 1, 0)), class = data.frame, .Names = c(householdid.x,                                                                                             nhouse, idno, rs, occ), row.names = c(NA, -20L))Here are my loops - slow and cumbersome:countcouples = list()countcouples$both <- 0countcouples$unique <- 0countcouples$zero <- 0for(i in 1:nrow(d)){  if(d$rs[i] == 1 & d$occ[i] == 1)  {countcouples$both <- countcouples$both+1}  if((d$rs[i] != 1 & d$occ[i] == 1) | (d$rs[i] == 1 & d$occ[i] != 1))  {countcouples$unique <- countcouples$unique+1}  if(d$rs[i] == 0 & d$occ[i] == 0)  {countcouples$zero <- countcouples$zero+1}}Here are the results:  both unique zero    2      4   14Any advice?
Calculate number of co-occurrences for two vectors
performance;r
Sure, use sum and compare all the lists directly:countcouples = list(    both = sum(d$rs == 1 & d$occ == 1),    unique = sum((d$rs != 1 & d$occ == 1) | (d$rs == 1 & d$occ != 1)),    zero = sum(d$rs == 0 & d$occ == 0))d$rs == 1 gives you a boolean vector, sum treats TRUE as 1, so the combination allows for much more succinct code.  It could also be further optimised by reusing the individual results.I also took the liberty to create the list directly instead of assigning results one by one.If you only have 0/1 as values, consider using d$rs & d$occ and so on directly as well.