Q:

Combining Tables Based On Condition

Can I find out if there is any code that creates a table or data frame that binds multiple tables for me? 
table(df$col1)
table(df$col1,df$col2<0)
table(df$col1,df$col3>0)
table(df$col1,df$col4>0)

In the above example, I am grouping my dataset based on similar values in df$col1 and displaying data that satisfy the condition df$col2<0.  What I get is a true and false matrix of the number of records fulfilling the condition and not.  I want a combined table that still groups the data by df$col1 and shows the true condition for df$col2<0,df$col3>0 and df$col4>0 in the same table.  

A:

Based on the description, we could do a cbind
r1 <- cbind(table(df$col1), table(df$col1,df$col2<0)[,2],
     table(df$col1,df$col3>0)[,2], table(df$col1,df$col4>0)[,2]) 

If there are many columns, this can be done by looping
r2 <- do.call(cbind, c(list(col1 = table(df$col1)), Map(function(x, y)  
     table(df$col1, get(y)(x, 0))[,2], df[-1], c("<", ">", ">"))))

all.equal(r1, r2, check.attributes = FALSE)
#[1] TRUE

We can also do this with group by operations. 
library(dplyr)
df %>% 
    mutate(col2 = col2 < 0) %>%
    mutate_at(3:4, funs(.  > 0)) %>% 
    group_by(col1) %>% 
    mutate(n = n()) %>%
    group_by(n, add = TRUE) %>% 
    summarise_all(sum)

data
set.seed(24)
df <- as.data.frame(matrix(sample(-2:5, 10*4, replace = TRUE), ncol=4))
names(df) <- paste0("col", 1:4)

