phibble

Functions and methods

Every public function and method, by task. Methods marked all tables are part of the Table contract and exist on DataFrame, SqlTable, and PolarsTable.

Creating and loading tables

Functions

Function or method Kind Purpose
tibble() function Build a DataFrame from named arguments, one per column, as tibble’s tibble().
tribble() function Build a DataFrame from column names, then rows, as tibble’s tribble().
as_tibble() function Convert tables, rows, columns, or collections into a DataFrame, as tibble’s as_tibble().
enframe() function An array as a two-column DataFrame of names and values, as tibble’s enframe().
tbl() function A lazy SqlTable, as dbplyr’s tbl().
polars() function A PolarsTable from any Table, or from anything as_tibble() accepts.

DataFrame

Function or method Kind Purpose
DataFrame::fromRows() static method Build a DataFrame from rows.
DataFrame::fromColumns() static method Build a DataFrame from columns: name => list of values, or name => Column.
DataFrame::fromCsv() static method Read delimited text like readr::read_csv(): a path (“.gz” is decompressed), an http:// or https:// URL (downloaded to a temporary file first), or an open stream.
DataFrame::fromCsvString() static method Read delimited text from a string; options as fromCsv().
DataFrame::fromCsvChunked() static method Read delimited text in chunks, as readr::read_delim_chunked(): each chunk of at most $chunkSize rows is passed to $callback with the 1-based index of its first row.
DataFrame::csvChunks() static method The chunks fromCsvChunked() reads, as a generator keyed by the 1-based index of each chunk’s first row.
DataFrame::fromJson() static method Read JSON: a list of records ([{“a”: 1}, …]) or an object of columns ({“a”: [1, 2]}).
DataFrame::fromPdo() static method Run a query and load the result.
DataFrame::fromQuery() static method Load the result of a Laravel query builder (query or Eloquent) or a Doctrine DBAL QueryBuilder.
DataFrame::fromCollection() static method Build a DataFrame from a Laravel Collection (or anything with all() or toArray(), or any iterable).
DataFrame::fromSource() static method Read a Phibble\Source\Source, such as a CsvSource or PdoSource, into a DataFrame.
DataFrame::tibble() static method Build a DataFrame column by column, as tibble’s tibble().
DataFrame::tribble() static method Build a DataFrame row by row, as tibble’s tribble().
DataFrame::asTibble() static method Convert tables, rows, columns, collections, or other iterables into a DataFrame, as tibble’s as_tibble().
DataFrame::enframe() static method An array as a two-column DataFrame of names and values, as tibble’s enframe().

SqlTable

Function or method Kind Purpose
SqlTable::table() static method A table (or view) by name.
SqlTable::query() static method Any SELECT query with positional (?) or named (:name) bindings.
SqlTable::fromQuery() static method A Laravel or Doctrine DBAL query builder, kept lazy.
SqlTable::fromSource() static method A lazy table over a PdoSource’s query and bindings.

PolarsTable

Function or method Kind Purpose
PolarsTable::fromTable() static method Copy any phibble table into Polars, keeping types, groups and factor levels.
PolarsTable::fromPolars() static method Wrap a Polars DataFrame; a LazyFrame is collected.

Rows and columns

Size and names

Function or method Kind Purpose
->columns() method, all tables Column names in order.
->types() method, all tables Column types by name.
->type() method, DataFrame One column’s type.
->nrow() method, all tables Number of rows.
->ncol() method, all tables Number of columns.
->count() method, all tables Number of rows, for count($df).
->has() method, DataFrame Whether the column exists.

Values

Function or method Kind Purpose
->column() method, all tables One column’s values as a PHP list.
->row() method, DataFrame One row by 0-based position.
Row->get() method One value by column name.
Row->has() method Whether the row has the column.
Row->toArray() method The row as an associative array of column name => value.

Selecting and renaming

Function or method Kind Purpose
->select() method, all tables Keep the named columns, in the given order.
->rename() method, all tables Rename columns.
NameRepair::repair() static method Repair column names, as vctrs::vec_as_names().

Filtering and sorting

Function or method Kind Purpose
->filter() method, all tables Keep rows where the predicate is true.
->arrange() method, all tables Sort rows.
->distinct() method, all tables Unique rows over the named columns, keeping the first of each and only those columns.
->dropNa() method, DataFrame Drop rows with NA in any of the named columns (all columns when empty).

Adding columns and rows

Function or method Kind Purpose
->mutate() method, all tables Add or replace columns.
->withColumn() method, DataFrame Add or replace one column.
->addColumn() method, DataFrame Insert columns, as tibble’s add_column(), with tibble()’s recycling rules.
->addRow() method, DataFrame Insert rows, as tibble’s add_row().

Rows by position

Function or method Kind Purpose
->slice() method, all tables Rows from $offset, $length of them or to the end.
->head() method, all tables The first $n rows.
->tail() method, DataFrame The last n rows; a negative n drops the first |n| rows, as in R.
->take() method, all tables Rows by 0-based position, in the given order.

Grouping and summaries

Grouping

Function or method Kind Purpose
->groupBy() method, all tables Set the grouping columns, replacing any existing grouping.
->ungroup() method, all tables Remove the grouping, including rowwise grouping.
->groups() method, all tables The grouping columns.
->dropsEmptyGroups() method, all tables Whether empty groups are dropped.
->ngroups() method, DataFrame Number of groups (1 for an ungrouped table, nrow for a rowwise one).
->rowwise() method, all tables Treat each row as its own group, as dplyr’s rowwise().
->isRowwise() method, all tables Whether the table is rowwise.

Summaries

Function or method Kind Purpose
->summarise() method, all tables One row per group: the group keys, then one column per entry.
->summarize() method, all tables Alias of summarise().

Per-group operations

Function or method Kind Purpose
->filterGroups() method, all tables Keep rows by a predicate that runs once per group.
->mutateGroups() method, all tables Add or replace columns with closures that run once per group.
->eachGroup() method, all tables Each group’s key and rows as an ungrouped table, in sorted key order.
->groupRows() method, all tables Each group’s key and 0-based row indexes, in the order of eachGroup().

Joins and reshaping

Joins

Function or method Kind Purpose
->join() method, all tables Join another table, with dplyr 1.1 semantics.

Binding

Function or method Kind Purpose
DataFrame::concat() static method Stack tables by row, matching columns by name.
DataFrame::bindCols() static method Put tables side by side, as dplyr’s bind_cols().

Reshaping

Function or method Kind Purpose
->pivotLongerSpec() method, all tables Pivot columns into rows from a spec, as tidyr’s pivot_longer_spec().
->pivotWiderSpec() method, all tables Pivot rows into columns from a spec, as tidyr’s pivot_wider_spec().
->nest() method, DataFrame tidyr::nest(): collapse columns into a list-column of tables, one row per unique combination of the other columns (first-appearance order).
->unnest() method, DataFrame tidyr::unnest(): expand list-columns of tables (or lists of rows) into rows.

Expression functions

Columns and literals

Function or method Kind Purpose
col() function Reference to the column with the given name.
lit() function Literal value as an expression.
call() function Call to any registered function by name, such as call(‘str_sub’, col('s'), 1, 3).
desc() function Descending sort key for arrange(), the first argument of a ranking function, or order_by.

Operators

Function or method Kind Purpose
Expr->add() method Sum of this expression and $other.
Expr->sub() method Difference of this expression and $other.
Expr->mul() method Product of this expression and $other.
Expr->div() method Quotient of this expression and $other, always a float.
Expr->mod() method Remainder of this expression divided by $other, with the sign of $other.
Expr->pow() method This expression raised to the power $other, as a float.
Expr->neg() method Negation of this expression.
Expr->eq() method Whether this expression equals $other.
Expr->ne() method Whether this expression differs from $other.
Expr->lt() method Whether this expression is less than $other.
Expr->le() method Whether this expression is less than or equal to $other.
Expr->gt() method Whether this expression is greater than $other.
Expr->ge() method Whether this expression is greater than or equal to $other.
Expr->and() method Logical AND of this expression and $other.
Expr->or() method Logical OR of this expression and $other.
Expr->not() method Logical negation of this expression.
Expr->isNa() method Whether each value is NA.
Expr->isIn() method Whether each value is one of the given values.
Expr->between() method Whether each value lies between $low and $high, inclusive.
Expr->desc() method Descending sort key on this expression, for arrange(), the first argument of a ranking function, or order_by.

Conditionals and missing values

Function or method Kind Purpose
is_na() function Whether each value is NA.
if_else() function Value of $true where the condition holds and of $false where it does not.
case_when() function Value paired with the first condition that holds, as case_when(cond1, value1, cond2, value2, ..., default: value).
coalesce() function First value that is not NA among the arguments, row by row.
between() function Whether each value lies between $low and $high, inclusive.
na_if() function Values of $x, with NA where $x equals $y.
near() function Whether $x and $y are equal within a tolerance.

Math

Function or method Kind Purpose
abs() function Absolute value.
sqrt() function Square root.
exp() function Exponential function, e raised to the power $x.
log() function Logarithm, natural by default.
log10() function Base-10 logarithm.
round() function Value rounded to a number of decimal digits.
floor() function Largest whole number not greater than the value, as a float.
ceiling() function Smallest whole number not less than the value, as a float.

Conversion

Function or method Kind Purpose
as_int() function Values converted to integers.
as_float() function Values converted to floats.
as_string() function Values converted to strings.
as_bool() function Values converted to logicals.

Aggregates

Function or method Kind Purpose
n() function Number of rows in the group.
sum() function Sum of the values.
mean() function Mean of the values.
median() function Median of the values.
min() function Smallest of the values.
max() function Largest of the values.
sd() function Sample standard deviation of the values.
var_() function Sample variance of the values.
quantile() function Sample quantile of the values at probability $p.
iqr() function Interquartile range of the values: the 0.75 quantile minus the 0.25 quantile.
n_distinct() function Number of distinct values, or of distinct combinations across several arguments.
first() function First value in the group.
last() function Last value in the group.
nth() function Value at position $n in the group.
any() function Whether any value is true.
all() function Whether every value is true.

Window functions

Function or method Kind Purpose
lag() function Value from n rows earlier in the group.
lead() function Value from n rows later in the group.
row_number() function Row number within the group, or the rank of each value with ties broken by row order.
min_rank() function Rank of each value, ties sharing the lowest rank, with gaps after ties.
dense_rank() function Rank of each value, ties sharing a rank, with no gaps after ties.
percent_rank() function Minimum rank rescaled to the range 0 to 1: (min_rank - 1) / (m - 1), where m is the number of non-NA values.
cume_dist() function Cumulative distribution: the share of non-NA values less than or equal to each value.
ntile() function Bucket number from 1 to n, splitting the ordered values into n groups as evenly as possible.
cumsum() function Cumulative sum in row order.
cumprod() function Cumulative product in row order.
cummean() function Cumulative mean in row order.
cummin() function Cumulative minimum in row order.
cummax() function Cumulative maximum in row order.
cumall() function Whether every value so far, in row order, is true.
cumany() function Whether any value so far, in row order, is true.
consecutive_id() function Run identifier that starts at 1 and increases each time the value, or combination of values, changes from the previous row.

Expression objects

Function or method Kind Purpose
Expr::of() static method PHP value wrapped as a literal expression; an expression is returned unchanged.
Expr::fromArray() static method Expression rebuilt from the array form that toArray() returns.
Expr->toArray() method JSON-friendly description of the expression tree.
Expr->columns() method Names of the columns the expression reads, in order of first use.

String and date functions

Strings

Function or method Kind Purpose
str_length() function Number of characters in the string.
str_lower() function String in lower case.
str_upper() function String in upper case.
str_to_lower() function String in lower case, by Unicode rules.
str_to_upper() function String in upper case, by Unicode rules.
str_to_title() function String in title case.
str_trim() function String with leading and trailing white space removed.
str_squish() function String with white space trimmed from both ends and each inner run collapsed to one space.
str_pad() function String padded to at least $width characters.
str_trunc() function String truncated to at most $width characters, ellipsis included.
str_sub() function Substring from position $start to position $end, inclusive.
paste() function Arguments joined into one string with a separator.
paste0() function Arguments joined into one string with no separator.

Patterns

Function or method Kind Purpose
fixed() function Pattern that matches its text literally.
regex() function Regular-expression pattern with options.
str_detect() function Whether the string contains a match for the pattern.
str_starts() function Whether the string starts with a match for the pattern.
str_ends() function Whether the string ends with a match for the pattern.
str_count() function Number of matches of the pattern in the string.
str_extract() function First match of the pattern in the string.
str_extract_all() function Every match of the pattern in the string, as a list.
str_replace() function String with the first match of the pattern replaced.
str_replace_all() function String with every match of the pattern replaced.
str_split() function Pieces of the string split at each match of the pattern, as a list.
str_split_i() function Piece $i of the string split at each match of the pattern.

Parsing dates

Function or method Kind Purpose
ymd() function Date parsed from text with year, month, and day in that order.
dmy() function Date parsed from text with day, month, and year in that order.
mdy() function Date parsed from text with month, day, and year in that order.
ymd_hms() function Datetime parsed from text with year, month, day, hour, minute, and second in that order.
dmy_hms() function Datetime parsed from text with day, month, year, hour, minute, and second in that order.
mdy_hms() function Datetime parsed from text with month, day, year, hour, minute, and second in that order.
parse_date_time() function Datetime parsed from text by the first of the given orders that fits.

Date parts

Function or method Kind Purpose
year() function Year of the date or datetime.
quarter() function Quarter of the year, from 1 to 4.
month() function Month of the date or datetime, from 1 to 12.
day() function Day of the month, from 1 to 31.
wday() function Day of the week, from 1 to 7.
yday() function Day of the year, from 1 to 366.
hour() function Hour of the datetime or time, from 0 to 23.
minute() function Minute of the datetime or time, from 0 to 59.
second() function Second of the datetime or time, with any fraction.

Rounding and differences

Function or method Kind Purpose
floor_date() function Date or datetime rounded down to the start of its unit.
ceiling_date() function Date or datetime rounded up to the start of the next unit.
round_date() function Date or datetime rounded to the nearer of floor_date() and ceiling_date().
difftime() function Difference $x - $y between two dates or datetimes, as a float in the given units.

Periods

Function or method Kind Purpose
seconds() function Period of $n seconds, to add to or subtract from a date or datetime.
minutes() function Period of $n minutes, to add to or subtract from a date or datetime.
hours() function Period of $n hours, to add to or subtract from a date or datetime.
days() function Period of $n days, to add to or subtract from a date or datetime.
weeks() function Period of $n weeks, to add to or subtract from a date or datetime.
months() function Period of $n months, to add to or subtract from a date or datetime.
years() function Period of $n years, to add to or subtract from a date or datetime.

Time zones and the clock

Function or method Kind Purpose
with_tz() function Same instant shown in another time zone.
force_tz() function Same clock time in another time zone, which changes the instant.
today() function Current date.
now() function Current date and time.
Clock::freeze() static method Fix the time that today() and now() read.
Clock::now() static method The current time in UTC, or the frozen time.

Types and conversion

Column types

Function or method Kind Purpose
->cast() method, DataFrame Convert columns to other types.
Type::parse() static method A Type from a case or its name, such as ‘float’ or ‘date’, in any letter case.
Type->abbreviation() method The short label printed in a column header, as in tibble: dbl, int, lgl, chr, fct, date, dttm, time, or list.
Type->isNumeric() method Whether the type is numeric: float, int, or bool.

Factors

Function or method Kind Purpose
->asFactor() method, DataFrame Turn a column into a factor, as R’s factor().
->asOrdered() method, DataFrame Convert a column to an ordered factor, as R’s factor(ordered = TRUE).
->isOrdered() method, DataFrame Whether the column is an ordered factor.
->levels() method, DataFrame The levels of a factor column, in level order.
->fctLevels() method, DataFrame factor(x, levels = ...): set the full level order.
->fctRelevel() method, DataFrame Move levels to the front, or after a 0-based position (-1 for the end), as forcats’ fct_relevel().
->fctRev() method, DataFrame fct_rev()
->fctInorder() method, DataFrame fct_inorder()
->fctInfreq() method, DataFrame fct_infreq()
->fctReorder() method, DataFrame Order levels by a summary (default median) of another column, as forcats’ fct_reorder().
->fctRecode() method, DataFrame Rename levels, new => old, as forcats’ fct_recode().
->fctCollapse() method, DataFrame Merge levels, new => list of old, as forcats’ fct_collapse().
->fctDrop() method, DataFrame fct_drop() / droplevels(): remove unused levels.

Times of day

Function or method Kind Purpose
Time::of() static method A time from hours, minutes, and seconds, as hms::hms().
Time::fromSeconds() static method A time from a number of seconds, rounded to the microsecond.
Time::parse() static method Text such as “07:30”, “7:30:15.25”, “-01:00:00”, “100:00:00”, or “1:30 PM” as a time, or null when it is not one.
Time::meridiem() static method readr’s AM/PM rule: 12 AM is hour 0, and PM adds 12 hours to any hour but 12.
Time->seconds() method The number of seconds, as R’s as.numeric() of an hms.
Time->hour() method The hour of the day, 0 to 23, as lubridate::hour().
Time->minute() method The minute of the hour, as lubridate::minute().
Time->second() method The second of the minute, with its fraction, as lubridate::second().

Model data

Function or method Kind Purpose
->toModelData() method, DataFrame Columns for model fitting with formulas (Phit\fit_ols, Phit\fit_generalized_linear, Phit\model_matrix):
->toMatrix() method, DataFrame Rows of numeric columns as floats, the shape phit’s fit_* functions take for x.
->toVector() method, DataFrame A numeric column as floats, the shape phit’s fit_* functions take for y.

Output

PHP values

Function or method Kind Purpose
->toRows() method, all tables The rows as a list of associative arrays.
->toColumns() method, all tables The columns as an array of PHP lists, keyed by name.
->collect() method, all tables The rows as an in-memory DataFrame.
->deframe() method, DataFrame A two-column DataFrame as a name => value array, or a one-column DataFrame as a list, as tibble’s deframe().
deframe() function A two-column DataFrame as a name => value array, or a one-column DataFrame as a list, as tibble’s deframe().
->toCollection() method, DataFrame An Illuminate\Support\Collection of row arrays.

CSV and JSON

Function or method Kind Purpose
->toCsv() method, DataFrame The CSV text writeCsv() would write.
->writeCsv() method, DataFrame Write CSV like readr::write_csv(): NA as “NA”, quoting only where needed, ISO dates, UTC datetimes with “Z”, TRUE/FALSE, and numbers in readr’s shortest form.
->toJson() method, DataFrame JSON as a list of records (‘records’) or an object of columns (‘columns’).

Printing

Function or method Kind Purpose
->__toString() method, DataFrame, SqlTable The table printed as tibble prints it, for echo $df.
->format() method, DataFrame Print like a tibble.
->glimpse() method, DataFrame One line per column with its type and leading values, as tibble’s glimpse().

SqlTable, PolarsTable, and Laravel

SqlTable

Function or method Kind Purpose
->showQuery() method, SqlTable The SQL that collect() would run, with ?
->bindings() method, SqlTable The values of the ?
->dialect() method, SqlTable The SQL dialect the table compiles to, chosen from the PDO driver.
Dialect::for() static method The dialect for a PDO connection: SQLite, PostgreSQL, or MySQL.
Dialect::tryFor() static method The dialect for a PDO connection, or null for a driver SqlTable does not support.

PolarsTable

Function or method Kind Purpose
->polars() method, PolarsTable The underlying Polars DataFrame.

Laravel

Function or method Kind Purpose
PhibbleServiceProvider::registerMacros() static method Register the macros; safe to call more than once.
->phibble() Laravel macro A lazy SqlTable over a Laravel query, Eloquent, or relation builder, on the builder’s connection.
->toDataFrame() Laravel macro Run a Laravel query, or read a collection, into a DataFrame.

Not listed

  • offsetExists: ArrayAccess: $df['name'] and $row['name'] read a column or value; writing throws, because tables are immutable.
  • offsetGet: ArrayAccess, as above.
  • offsetSet: ArrayAccess, as above.
  • offsetUnset: ArrayAccess, as above.
  • getIterator: IteratorAggregate: foreach over a table yields a Row per row.
  • DataFrame::storage: Returns the internal column storage.
  • Time::jsonSerialize: JsonSerializable: a time encodes as its HH:MM:SS text.
  • Time::__toString: Stringable: a time casts to its HH:MM:SS text.
  • Type::cases: Built-in enum method.
  • Type::from: Built-in enum method.
  • Type::tryFrom: Built-in enum method.
  • PhibbleServiceProvider::boot: Laravel service provider hook.
  • Dialect::*: SQL compiler hooks that each dialect class implements; only Dialect::for() and Dialect::tryFor() are for applications.