Search code examples
rlogical-operatorsboolean-logictruthtable

Possible combinations using R


I have edited my question and changed certain lines in my script, to make it clear to find the number of times I can get the output 1 or 0.

I have 19 variables.I tried the possible combinations of these 19 variables for giving a binary output of 0 or 1 i.e. 2 to the power of 19 (5,24,288). But I couldn't display the truth table in R for all the 5,24,288 combinations because of the limited memory space. Is there any way to find the number of combinations that give the output 1 and 0. Below is the script, where I have given the following inputs using logical gate AND and OR. Kindly give me ideas or suggestions to find the number of times I can get values 0 or 1 as output

    n <- 19
    l <- rep(list(0:1), n)
    inputs <- expand.grid(l)
    len <-dim(inputs)
    len <-len[1]
    output <- 1;
    for(i in 1:len)
    {
    if((inputs[i,1] == 1 & inputs[i,2] == 1 & inputs[i,3] == 1 &    (inputs[i,4] == 1 & inputs[i,5] == 1 | inputs[i,6] == 1 & inputs[i,7] == 0)) | (inputs[i,1] == 1 & inputs[i,2] == 1 & inputs[i,8] == 1 & inputs[i,9] == 1) | (inputs[i,1] == 1 & inputs[i,10] == 0 & inputs[i,11] == 0) |(inputs[i,1] == 1 & inputs[i,12] == 1 & inputs[i,13] == 1 & inputs[i,14] == 1) | (inputs[i,1] == 1 & inputs[i,15] == 1 & inputs[i,16] == 1) | (inputs[i,1] == 1 & inputs[i,17] == 0) | (inputs[i,1] == 1 & inputs[i,18] == 1 & inputs[i,19] == 1)){
   output[i] <- 1
   }
   else
   {
   output[i] <- 0
   }
   }
   data <- cbind(inputs, output)
   write.csv(data, "data.csv", row.names=FALSE)

Solution

  • 1048576 isn't absurdly big. If all you want are the 20 0/1 columns it takes about 80 Mb if you use integers:

    x = replicate(n = 20, expr = c(0L, 1L), simplify = FALSE)
    comb = do.call(expand.grid, args = x)
    
    dim(comb)
    # [1] 1048576      20
    
    format(object.size(comb), units = "Mb")
    # [1] "80 Mb"
    

    In your question you use && a lot. && is good for comparing something of length 1. Use & for a vectorized comparison so you don't need a for loop.

    For example:

    y = matrix(c(1, 1, 0, 0, 1, 0, 1, 0), nrow = 4)
    y[, 1] & y[, 2] # gives the truth table for & applied across columns
    # no for loop needed
    # R will interpret 0 as FALSE and non-zero numbers as TRUE
    # so you don't even need the == 1 and == 0 parts.
    

    It seems like you're really after the number of combinations where all the values are 1. (Or where they all have specific values.) I'm not going to give away the answer here because I suspect this is for homework, but I will say that you shouldn't need to program a single line of code to find that out. If you understand what the universe of 'all possible combinations' is, the answer will be quite clear logically.