Reputation: 9313
I want to construct a truthtable with R tidyverse functions mutate()
, case_when()
and expand_grid()
.
Here I define a custom operator %->%
for the "conditional" logical connective
(->
, "if p then q" AKA "p imples q".)
I also try to consider R's three-value logic.
Is the following code correct?
Is my %->%
already taken by some other common package?
library(tidyverse)
values <- c(TRUE, FALSE, NA)
`%->%` <- function(p,q) {
case_when((p & q) ~ TRUE,
(p & !q) ~ FALSE,
(p & is.na(q)) ~ TRUE,
(!p & q) ~ FALSE, # not sure about this one
(!p & !q) ~ TRUE,
(!p & is.na(q)) ~ NA,
(is.na(p) & q) ~ NA,
(is.na(p) & !q) ~ TRUE,
(is.na(p) & is.na(q)) ~ NA,
#unhandled case, this line should never be reached
TRUE ~ NA )}
tt <- expand_grid(p = values, q = values) %>%
mutate(`p|q` = p | q,
`p&q` = p & q,
`p->q` = p %->% q) %>%
select(p, q, `p->q`)
tt
Result:
R> tt
# A tibble: 9 × 3
p q `p->q`
<lgl> <lgl> <lgl>
1 TRUE TRUE TRUE
2 TRUE FALSE FALSE
3 TRUE NA TRUE
4 FALSE TRUE FALSE # not sure about this one
5 FALSE FALSE TRUE
6 FALSE NA NA
7 NA TRUE NA
8 NA FALSE TRUE
9 NA NA NA
Is there a built-in R operator (or a go-to package on CRAN ) for the conditional that I don't know about (faster, more rigorously tested, vectorized, generic...)?
(I have intermediate R skills and I am a beginner in logic)
Update 2022 : I have rewritten the function/truthtable according to a Book (J.Celko, Data&Databases, Morgan Kaufman Publ, 1999)
Upvotes: 0
Views: 114