Skip to content
Prev 390989 / 398506 Next

Is there a Truth Table Generator in R?

I played around and dame up with the following raw idea for truth tables


library(tidyverse)


truth_table_inputs <- 
  function(n){
  if (n==1) return(
    tibble(x1=c(FALSE,TRUE)))
  expand_grid(truth_table_inputs(n-1),
              last_var=c(FALSE,TRUE)) ->
    res
  names(res) <- paste0("x",1:n)
  res              
}


```{r}
eval_truth_table <-
  function(n,fun){
    truth_table_inputs(n) |>
      bind_cols(
    truth_table_inputs(n) |>
      rowwise() |>
      (\(x)do.call(fun,as.list(x)))()
      ) -> res
    names(res)[n+1] <-
      deparse(substitute(fun))
    res
  } 

Example

eval_truth_table(3,function(x1,x2,x3)x1&x2|x3)

If there are more inputs than the function consumes, use dots

eval_truth_table(3,function(x1,x2,...)x1&x2)