Boolean

Instance of:

AKA: Bool

Distinct from:

English:

Formalization:

\[ \]

Cites: Wikipedia) ; Wikidata

Code

Imports and spin up toy data objects and databases.
toy_vector_numeric <- c(1,2,3,4,5)
toy_vector_character <- c('a','b','c','d','e')
toy_matrix <- matrix(1:9, nrow=3,ncol=3)
toy_list <- list('a','1',T,c('red','green'))
toy_df <- data.frame(id=c('unit1','unit2','unit3'), y=c(1,2,3), x= c(3,2,1))

toy_dirty_df <- data.frame(id=c('','NA','NaN','inf'), y=c(1,2,3,4), x= c(0,NA,NaN,Inf)) #can't explicitly include NULL 

library(data.table)
toy_dt <- data.table(id=c('unit1','unit2','unit3'), y=c(1,2,3), x= c(3,2,1))
toy_dirty_dt <- as.data.table(toy_dirty_df)
library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.5.0 
✔ readr   2.1.3      ✔ forcats 0.5.2 
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::between()   masks data.table::between()
✖ dplyr::filter()    masks stats::filter()
✖ dplyr::first()     masks data.table::first()
✖ dplyr::lag()       masks stats::lag()
✖ dplyr::last()      masks data.table::last()
✖ purrr::transpose() masks data.table::transpose()
library(arrow)

Attaching package: 'arrow'

The following object is masked from 'package:utils':

    timestamp
import numpy as np
toy_vector_numeric = np.array([1,2,3,4,5])
toy_vector_character = np.array(['a','b','c','d','e'])
toy_list = ['a','1',True,['red','green']]
toy_dictionary = { 'a':1 , 'b':2, 'c':3}

from jax import numpy as jnp
toy_vector_numeric_jax = jnp.array([1,2,3,4,5])
#toy_vector_character_jax = jnp.array(['a','b','c','d','e']) #only numeric is allowed in jax
WARNING:jax._src.lib.xla_bridge:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
import pandas as pd
toy_df = pd.DataFrame(data={'id': ['unit1','unit2','unit3'], 'y': [1, 2, 3], 'x': [3, 2, 1]})

import torch

import tensorflow as tf

import pyarrow as pa
library(DBI)
# Create an ephemeral in-memory RSQLite database
#con <- dbConnect(RSQLite::SQLite(), dbname = ":memory:")
#dbListTables(con)
#dbWriteTable(con, "mtcars", mtcars)
#dbListTables(con)

#Configuration failed because libpq was not found. Try installing:
#* deb: libpq-dev libssl-dev (Debian, Ubuntu, etc)
#install.packages('RPostgres')
#remotes::install_github("r-dbi/RPostgres")
#Took forever because my file permissions were broken
#pg_lsclusters
require(RPostgres)
# Connect to the default postgres database
#I had to follow these instructions and create both a username and database that matched my ubuntu name
#https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart
con_Postgres <- dbConnect(RPostgres::Postgres())

DROP TABLE IF EXISTS toy_df;

CREATE TABLE IF NOT EXISTS toy_df (
  id varchar(5),
    y INTEGER,
    x INTEGER
);

INSERT INTO toy_df (id, y, x)
VALUES
    ('unit1',1,3),
    ('unit2',2,2),
    ('unit3',3,1);
    
#install.packages("duckdb")
library("DBI")
con_duckdb = dbConnect(duckdb::duckdb(), ":memory:")
#pip install duckdb==0.6.0
import duckdb
con_duckdb = duckdb.connect()

0.1 R

Base

Logical Vectors

TRUE
[1] TRUE
FALSE
[1] FALSE
T; F
[1] TRUE
[1] FALSE
logical(length = 0)
logical(0)
as.logical(1)
[1] TRUE
is.logical(1)
[1] FALSE
## non-zero values are TRUE
as.logical(c(pi,0))
[1]  TRUE FALSE
if (length(letters)) cat("26 is TRUE\n")
26 is TRUE
## logical interpretation of particular strings
charvec <- c("FALSE", "F", "False", "false",    "fAlse", "0",
             "TRUE",  "T", "True",  "true",     "tRue",  "1")
as.logical(charvec)
 [1] FALSE FALSE FALSE FALSE    NA    NA  TRUE  TRUE  TRUE  TRUE    NA    NA
## factors are converted via their levels, so string conversion is used
as.logical(factor(charvec))
 [1] FALSE FALSE FALSE FALSE    NA    NA  TRUE  TRUE  TRUE  TRUE    NA    NA
as.logical(factor(c(0,1)))  # "0" and "1" give NA
[1] NA NA
length(TRUE)
[1] 1

Tidyverse

DataTable

Arrow

Apache Arrow data types “These functions create type objects corresponding to Arrow types. Use them when defining a schema() or as inputs to other types, like struct. Most of these functions don’t take arguments, but a few do.”

library(arrow)
boolean()
Boolean
bool
bool()
Boolean
bool

0.2 Python

0.2.0.1 3.x / math/ statistics

Boolean Values Boolean Values Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

They are written as False and True, respectively.

type(True)
<class 'bool'>
type(1)
<class 'int'>

class bool(x=False)

class bool(x=False) Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise, it returns True. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).

bool(1)
True
bool(0)
False
bool('A')
True
bool(None)
False
1==True
True
'A'==True
False

TypeError: object of type ‘bool’ has no len() in Python


try:
    print(len(True))
except Exception as ex:
    print(ex)
object of type 'bool' has no len()

0.2.0.2 NumPy / SciPy / scikit-learn

np.array([[ True,  True],
       [ True,  True]], dtype=bool)
array([[ True,  True],
       [ True,  True]])

0.2.0.3 Pandas


pd.Series([True, False])
0     True
1    False
dtype: bool
pd.Series([True]).bool()
True
try:
    pd.Series([True, False]).bool() #Doesn't work on series with more than one value
except Exception as ex:
    print(ex)
    
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

0.3 Jax

jnp.array([[ True,  True],
       [ True,  True]], dtype=bool)
DeviceArray([[ True,  True],
             [ True,  True]], dtype=bool)

0.4 Numpyro

Uses jax’s boolean array

0.5 Stan

0.6 Torch

TENSOR ATTRIBUTES


torch.zeros(10, dtype=torch.bool)
tensor([False, False, False, False, False, False, False, False, False, False])
torch.zeros(10).bool()
tensor([False, False, False, False, False, False, False, False, False, False])

0.7 Tensorflow

Introduction to Tensors TensorFlow Data Types


print(tf.constant([True,False], dtype=tf.bool))
tf.Tensor([ True False], shape=(2,), dtype=bool)
try:
    print(tf.constant([1,0], dtype=tf.bool))
except Exception as ex:
    print(ex)
Cannot convert [1, 0] to EagerTensor of dtype bool
print(tf.cast(tf.constant([1,0]), tf.bool))
tf.Tensor([ True False], shape=(2,), dtype=bool)

0.8 PostgreSQL


DROP TABLE IF EXISTS bool_df;

CREATE TABLE IF NOT EXISTS bool_df (
  example_bool boolean
);

INSERT INTO bool_df (example_bool)
VALUES
  (NULL),
  (TRUE),
  ('t'),
  ('true'),
  ('y'),
  ('yes'), /* lol what? */
  ('on'),  /* lol what? */
  ('1'),
  (FALSE),
  ('f'),
  ('false'),
  ('n'),
  ('no'),  /* lol what? */
  ('off'); /* lol what? */
  

SELECT * from bool_df;
  
Displaying records 1 - 10
example_bool
NA
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE

0.9 DuckDB

Boolean Type


DROP TABLE IF EXISTS bool_df;

CREATE TABLE IF NOT EXISTS bool_df (
  example_bool boolean
);

INSERT INTO bool_df (example_bool)
VALUES
  (NULL),
  (TRUE),
  ('t'),
  ('true'),
  ('1'),
  (1),
  (15),
  (-1),
  (FALSE),
  ('f'),
  ('false'),
  ('0'),
  (0) ;

SELECT * from bool_df;
  
Displaying records 1 - 10
example_bool
NA
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE