Skip to content

Is there a Truth Table Generator in R?

13 messages · Paul Bernal, Ebert,Timothy Aaron, Spencer Graves +5 more

#
Dear friends,

Hope you are doing great. I have been searching for a truth table generator
in R, but everything I find has a Python implementation instead.

Maybe there is in fact a truth table generator in R, but I am not searching
in the right places?

Any help and/or guidance will be greatly appreciated.

Best regards,
Paul
#
Hi Paul,
Can you describe a truth table so that those persons who don't know your specific application might be able to help? Is possible that it is known by a different name? My first guess is confusion matrix.
Regards,
Tim

-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Paul Bernal
Sent: Saturday, March 12, 2022 11:42 AM
To: R <r-help at r-project.org>
Subject: [R] Is there a Truth Table Generator in R?

[External Email]

Dear friends,

Hope you are doing great. I have been searching for a truth table generator in R, but everything I find has a Python implementation instead.

Maybe there is in fact a truth table generator in R, but I am not searching in the right places?

Any help and/or guidance will be greatly appreciated.

Best regards,
Paul


______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Dhelp&d=DwICAg&c=sJ6xIWYx-zLMB3EPkvcnVg&r=9PEhQh2kVeAsRzsn7AkP-g&m=CtTRgVrLfmt90LZKdUbT_g6aHRJ-kVQogNxWfmzlUtgiW4qDeBreSVq1oI-5B09z&s=10AZl9R7fUIEB2c-nixiSLoAg9aergAyNJnwNoI_W-Y&e=
PLEASE do read the posting guide https://urldefense.proofpoint.com/v2/url?u=http-3A__www.R-2Dproject.org_posting-2Dguide.html&d=DwICAg&c=sJ6xIWYx-zLMB3EPkvcnVg&r=9PEhQh2kVeAsRzsn7AkP-g&m=CtTRgVrLfmt90LZKdUbT_g6aHRJ-kVQogNxWfmzlUtgiW4qDeBreSVq1oI-5B09z&s=UQzuG0nG_5HKiiR0wX2pUQfsc39cPZtYkKFkzBxuC2U&e=
and provide commented, minimal, self-contained, reproducible code.
#
library(sos)
tt <- findFn("{truth table}")
installPackages(tt)
tt


	  This just now opened two sheets in my default browser.  The first 
listed all the help pages in contributed packages with the phrase "truth 
table", sorted to put first the ones in packages with the most matches. 
  The second is a summary by package.


	  Hope this helps.
	  Spencer Graves
On 3/12/22 10:42 AM, Paul Bernal wrote:
#
both <- c( FALSE, TRUE )
tt <- expand.grid( C = both
                 , B = both
                 , A = both
                 )
tt <- tt[, 3:1 ]
On March 12, 2022 8:42:28 AM PST, Paul Bernal <paulbernal07 at gmail.com> wrote:

  
    
#
As Tim pointed out, your query is rather vague. A reprex would have
really helped here: please include them whenever possible in future
queries.

As Spencer said, a simple search would likely have yielded whatever
you were seeking. Do make such efforts before posting.

And as Jeff indicated, it's most likely straightforward to create a
function that does what you want de novo. Here is such a function
based on my guess of what you meant:

tt <- function(tabl, fun)
 {## fun is a function that when applied rowwise to
 ## the logical data frame tabl yields a
 ## logical result
 cbind(tabl, Result = apply(tabl,1,fun))
 }

## some examples
Var1  Var2 Result
1  TRUE  TRUE   TRUE
2 FALSE  TRUE   TRUE
3  TRUE FALSE   TRUE
4 FALSE FALSE  FALSE
Var1  Var2 Result
1  TRUE  TRUE   TRUE
2 FALSE  TRUE  FALSE
3  TRUE FALSE  FALSE
4 FALSE FALSE  FALSE
Var1  Var2 Result
1  TRUE  TRUE   TRUE
2 FALSE  TRUE   TRUE
3  TRUE FALSE  FALSE
4 FALSE FALSE   TRUE

Cheers,
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Sat, Mar 12, 2022 at 9:13 AM Jeff Newmiller <jdnewmil at dcn.davis.ca.us> wrote:
#
To the end of Jeff's program add
tt$truth <- tt$A & tt$B & tt$C
to evaluate the outcome of expand.grid. 

Tim

-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Jeff Newmiller
Sent: Saturday, March 12, 2022 12:05 PM
To: r-help at r-project.org; Paul Bernal <paulbernal07 at gmail.com>; R <r-help at r-project.org>
Subject: Re: [R] Is there a Truth Table Generator in R?

[External Email]

both <- c( FALSE, TRUE )
tt <- expand.grid( C = both
                 , B = both
                 , A = both
                 )
tt <- tt[, 3:1 ]
On March 12, 2022 8:42:28 AM PST, Paul Bernal <paulbernal07 at gmail.com> wrote:
--
Sent from my phone. Please excuse my brevity.

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Dhelp&d=DwICAg&c=sJ6xIWYx-zLMB3EPkvcnVg&r=9PEhQh2kVeAsRzsn7AkP-g&m=Cj0cRxlu_GS0ARzvxm-eD27PhuhkgT_azaq1hamiYDmCglHF8_9hGTAkcDNoZtUq&s=h0wdH7OvIxKWgjwFmBIGHvswAKy8VKwyyI3IbB9dKkc&e=
PLEASE do read the posting guide https://urldefense.proofpoint.com/v2/url?u=http-3A__www.R-2Dproject.org_posting-2Dguide.html&d=DwICAg&c=sJ6xIWYx-zLMB3EPkvcnVg&r=9PEhQh2kVeAsRzsn7AkP-g&m=Cj0cRxlu_GS0ARzvxm-eD27PhuhkgT_azaq1hamiYDmCglHF8_9hGTAkcDNoZtUq&s=tsrpB1zmIQL_wMcn70xPEkvpaisBrAM9k2OQ8kDrebw&e=
and provide commented, minimal, self-contained, reproducible code.
#
... Forgot to include for completeness: dat is as Jeff suggested:

both <- c(TRUE, FALSE)
dat <- expand.grid(both, both)

Bert Gunter
On Sat, Mar 12, 2022 at 10:33 AM Bert Gunter <bgunter.4567 at gmail.com> wrote:
#
...
tt$truth <- tt$A & tt$B & tt$C
to evaluate the outcome of expand.grid.

or, as I said,
tt$truth <- apply(tt,1, all)
which works for any number of columns in tt.


Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Sat, Mar 12, 2022 at 2:02 PM Ebert,Timothy Aaron <tebert at ufl.edu> wrote:
#
There are 2^(2^length(tt)) possible "truth" vectors for the inputs defined in tt. AND-ing all of the inputs only gives one of those possibilities. Some popular named cases for 2 inputs are shown here [1], but it is common to use combinations of !, & and | to specify a particular truth vector. There is also the problem of reverse-engineering such a boolean expeession [2] in simplest form from a given truth vector, but I don't know if anyone has implemented such algorithms in R.

[1] https://en.wikipedia.org/wiki/Truth_table

[2] https://en.wikipedia.org/wiki/Karnaugh_maps
On March 12, 2022 2:17:32 PM PST, Bert Gunter <bgunter.4567 at gmail.com> wrote:

  
    
#
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)
#
After slogging through lots of posts about a poorly defined request, I am left wondering if I missed the original sender properly explaining what THEY mean by a truth table and what it should look like.
Some here seem to know (or are guessing) that the request is to make all combinations of TRUE and FALSE for N columns in a data.frame and some for an indefinite value of N. Some others may also want to throw in additional columns that reflect a logical AND operation and perhaps others.
So I calmly request someone tell us what the real request is so I can evaluate if anything said here makes much sense in answering the real request.
As I see it, if you have 2 columns, there are four possible combination in what amounts to a 4x2 matrix. If your mailer allows my text to be seen as intended, the following shows combinations starting with F, albeit a table starting with T is equivalent in terms of meaning:
FFFTTFTT

For an N=3 column it gets more rows using binary notation with T=0 and F=1 so 8 rows.
000001010011100101110111

The trend becomes clear that the number of rows is 2**N power so a simple approach (albeit there are other ways shown that may be simpler to code using existing software) is to note the pattern. The first column requires 2**N items alternating every (2**N)/2 times. Meaning if N=5 then you want 32 rows in the result with 16 units of F and then 16 units of T, or vice versa. The R function that does this easily (as part of a loop perhaps) is rep() and sample code (hopefully blank lines keep it from getting wrapped funny is something like this that can be simplified:
N <- 5
rows <- 2**N
TF <- data.frame(index=1:rows)
for (ind in rev(2**(N:1))) {??? TF <- cbind(TF, rep(c(TRUE, FALSE), each=rows/ind, length.out=rows))??}
names(TF) <- c("index", paste("col", 1:N, sep=""))
The above uses rep() repeatedly to produce runs of TRUE and FALSE of decreasing size and keeps concatenating them to an existing data.frame with cbind(). The result is a column with 16 TRUE followed by 16 FALSE then another column with 8 by 8 and repeated again as 8 by 8. The next column alternates in groups of 4 then the next in groups of two and finally alternating in "groups" of 1.
Obviously this can be wrapped up in a function that takes N as an argument and makes an arbitrary N column construct with 2**N rows as described and this may be what is wanted for the main table. I threw this together rapidly and I am sure can improve it so column names are created as appropriate.
For example, rather than cbind, the following would work well too:
colnm <- ...TF[colnm] <-?rep(c(TRUE, FALSE), each=rows/ind, length.out=rows)

But the question is whether this makes what is wanted, or needs something more like columns that represent whether the OR or AND or some other boolean function of N boolean items is TRUE or FALSE.
I repeat, the above analysis does not suggest other supplied solutions are bad or wrong, just a suggestion of how fairly simple functionality in R can do what is wanted. Of course, if something else is wanted, we are all wasting our time answering. I waited a while hoping not to need to or to reply to an actual question I know how to deal with.
-----Original Message-----
From: Jeff Newmiller <jdnewmil at dcn.davis.ca.us>
To: Bert Gunter <bgunter.4567 at gmail.com>; Ebert, Timothy Aaron <tebert at ufl.edu>
Cc: r-help at r-project.org <r-help at r-project.org>; Paul Bernal <paulbernal07 at gmail.com>
Sent: Sun, Mar 13, 2022 5:17 am
Subject: Re: [R] Is there a Truth Table Generator in R?

There are 2^(2^length(tt)) possible "truth" vectors for the inputs defined in tt. AND-ing all of the inputs only gives one of those possibilities. Some popular named cases for 2 inputs are shown here [1], but it is common to use combinations of !, & and | to specify a particular truth vector. There is also the problem of reverse-engineering such a boolean expeession [2] in simplest form from a given truth vector, but I don't know if anyone has implemented such algorithms in R.

[1] https://en.wikipedia.org/wiki/Truth_table

[2] https://en.wikipedia.org/wiki/Karnaugh_maps
On March 12, 2022 2:17:32 PM PST, Bert Gunter <bgunter.4567 at gmail.com> wrote:

  
    
#
I too have been wondering what "a truth table generator"
meant to the OP.  There are web sites like
https://web.stanford.edu/class/cs103/tools/truth-table-tool/
where you can type in a formula and it will display a
truth table with a column for each variable and a column for the result.
The last propositional problem I worked with had
about a hundred variables, so I am somewhat puzzled about
what use this would be in practice.   (Yes, I know a hundred
variables is a a very small problem these days.)

But then I found
https://www.r-bloggers.com/2021/05/learning-r-creating-truth-tables/

If this is what the OP's after, then it's not about
*using* a truth table generator but about how to *write*
one: how to parse a propositional formula, how to evaluate
one, how to make the grid, &c.


On Mon, 14 Mar 2022 at 08:34, Avi Gross via R-help <r-help at r-project.org>
wrote:

  
  
#
Richard, the second one made some sense to me as a practical application. The eval() of some random string scares me a bit, LOL!
As I see it, that task sounds like it wants you to parse the expression and find all unique alphabetic names in a formula and make a? table (something like a data.frame) using that set of names for the columns. Then you want to evaluate the formula in an environment where the names of the columns are available in an enriched environment. It looks straightforward enough and any of the methods we have described here might make the initial table and set the column names and then afterward add one (or if needed more) columns that implement whatever logical formula you want.
Of course, this being R, the formula could as easily produce a numeric result or other things but cannot contain various kinds of text like f(x) or %in% as those would be picked up and made into named columns! I might prefer a version where the formula is passed in as one argument and the variable names needed are passed as a vector or other list or as dots and then a wider array of arguments can be used, or even a request for multiple evaluations and so on.
BTW, I looked to see how my post looked after being forwarded through you and it is not a pleasure. Multiple lines of say?FF/FT/TF/TT? are collapsed into?FFFTTFTT. My lines of code were not left alone. This darn mailer has an option to always use plain text but when I do that, some complain lines are not wrapped and long lines need to be read by scrolling horizontally.
Can't win!

-----Original Message-----
From: Richard O'Keefe <raoknz at gmail.com>
To: Avi Gross <avigross at verizon.net>
Cc: r-help at r-project.org <r-help at r-project.org>
Sent: Sun, Mar 13, 2022 8:36 pm
Subject: Re: [R] Is there a Truth Table Generator in R?

I too have been wondering what "a truth table generator"meant to the OP.? There are web sites likehttps://web.stanford.edu/class/cs103/tools/truth-table-tool/where you can type in a formula and it will display atruth table with a column for each variable and a column for the result.? The last propositional problem I worked with hadabout a hundred variables, so I am somewhat puzzled aboutwhat use this would be in practice. ? (Yes, I know a hundredvariables is a a very small problem these days.)
But then I foundhttps://www.r-bloggers.com/2021/05/learning-r-creating-truth-tables/
If this is what the OP's after, then it's not about*using* a truth table generator but about how to *write*one: how to parse a propositional formula, how to evaluateone, how to make the grid, &c.
On Mon, 14 Mar 2022 at 08:34, Avi Gross via R-help <r-help at r-project.org> wrote:
After slogging through lots of posts about a poorly defined request, I am left wondering if I missed the original sender properly explaining what THEY mean by a truth table and what it should look like.
Some here seem to know (or are guessing) that the request is to make all combinations of TRUE and FALSE for N columns in a data.frame and some for an indefinite value of N. Some others may also want to throw in additional columns that reflect a logical AND operation and perhaps others.
So I calmly request someone tell us what the real request is so I can evaluate if anything said here makes much sense in answering the real request.
As I see it, if you have 2 columns, there are four possible combination in what amounts to a 4x2 matrix. If your mailer allows my text to be seen as intended, the following shows combinations starting with F, albeit a table starting with T is equivalent in terms of meaning:
FFFTTFTT

For an N=3 column it gets more rows using binary notation with T=0 and F=1 so 8 rows.
000001010011100101110111

The trend becomes clear that the number of rows is 2**N power so a simple approach (albeit there are other ways shown that may be simpler to code using existing software) is to note the pattern. The first column requires 2**N items alternating every (2**N)/2 times. Meaning if N=5 then you want 32 rows in the result with 16 units of F and then 16 units of T, or vice versa. The R function that does this easily (as part of a loop perhaps) is rep() and sample code (hopefully blank lines keep it from getting wrapped funny is something like this that can be simplified:
N <- 5
rows <- 2**N
TF <- data.frame(index=1:rows)
for (ind in rev(2**(N:1))) {??? TF <- cbind(TF, rep(c(TRUE, FALSE), each=rows/ind, length.out=rows))??}
names(TF) <- c("index", paste("col", 1:N, sep=""))
The above uses rep() repeatedly to produce runs of TRUE and FALSE of decreasing size and keeps concatenating them to an existing data.frame with cbind(). The result is a column with 16 TRUE followed by 16 FALSE then another column with 8 by 8 and repeated again as 8 by 8. The next column alternates in groups of 4 then the next in groups of two and finally alternating in "groups" of 1.
Obviously this can be wrapped up in a function that takes N as an argument and makes an arbitrary N column construct with 2**N rows as described and this may be what is wanted for the main table. I threw this together rapidly and I am sure can improve it so column names are created as appropriate.
For example, rather than cbind, the following would work well too:
colnm <- ...TF[colnm] <-?rep(c(TRUE, FALSE), each=rows/ind, length.out=rows)

But the question is whether this makes what is wanted, or needs something more like columns that represent whether the OR or AND or some other boolean function of N boolean items is TRUE or FALSE.
I repeat, the above analysis does not suggest other supplied solutions are bad or wrong, just a suggestion of how fairly simple functionality in R can do what is wanted. Of course, if something else is wanted, we are all wasting our time answering. I waited a while hoping not to need to or to reply to an actual question I know how to deal with.
-----Original Message-----
From: Jeff Newmiller <jdnewmil at dcn.davis.ca.us>
To: Bert Gunter <bgunter.4567 at gmail.com>; Ebert, Timothy Aaron <tebert at ufl.edu>
Cc: r-help at r-project.org <r-help at r-project.org>; Paul Bernal <paulbernal07 at gmail.com>
Sent: Sun, Mar 13, 2022 5:17 am
Subject: Re: [R] Is there a Truth Table Generator in R?

There are 2^(2^length(tt)) possible "truth" vectors for the inputs defined in tt. AND-ing all of the inputs only gives one of those possibilities. Some popular named cases for 2 inputs are shown here [1], but it is common to use combinations of !, & and | to specify a particular truth vector. There is also the problem of reverse-engineering such a boolean expeession [2] in simplest form from a given truth vector, but I don't know if anyone has implemented such algorithms in R.

[1] https://en.wikipedia.org/wiki/Truth_table

[2] https://en.wikipedia.org/wiki/Karnaugh_maps
On March 12, 2022 2:17:32 PM PST, Bert Gunter <bgunter.4567 at gmail.com> wrote: