Search code examples
rsparse-matrixtruthtable

How to create a truth table based on table of values in r


I am trying to create a script that will create a truth table based on different values.

Example

First table

The truth table for this would be

Truth table version of above table

I'm fairly new to r. I know it has a lot of great capabilities when it comes to data analysis, but this would help a lot. Was looking at potentially implementing something with sparse matrices, but I don't know.


Solution

  • Next time, please include data in your question, and avoid putting images.

    May be this using data.table:

    Data:

    library('data.table')
    df1 <- data.table(Name = c('Bob', 'Bob', 'Luke'),
                      Location = c('Texas', 'Ohio', 'Utah'),
                      Pet = c('Dog', 'Cat', 'Dog'),
                      Coder = c(1,0,1),
                      stringsAsFactors = FALSE )
    

    Code:

    df1[, id := .I ] # assign unique id, and later it will be removed
    select_cols <- c('Name', 'Location', 'Pet') # selected columns
    dcast( data = melt(df1, measure.vars = select_cols ),  
           formula = "id + Coder ~ value", 
           fun.aggregate = length, 
           fill = 0  )[, id := NULL ][]
    
    #    Coder Bob Cat Dog Luke Ohio Texas Utah
    # 1:     1   1   0   1    0    0     1    0
    # 2:     0   1   1   0    0    1     0    0
    # 3:     1   0   0   1    1    0     0    1