mutate() adds new columns or changes existing ones, as dplyr::mutate()
does. The expressions listed under "Supported expressions" are computed on
the GPU, within the limits stated there. A call with any other expression
runs in dplyr on the CPU, and its result comes back to the GPU.
Arguments
- .data
A
tbl_gpuobject created bytbl_gpu().- ...
Name-value pairs of expressions. The name gives the column name (new or existing), and the value is an expression involving existing columns and/or scalar values (see "Supported expressions" below).
- .by
Optional grouping columns for this call only (tidyselect), run on the GPU:
mutate(df, y = mean(x), .by = g)gives the same result asdf |> group_by(g) |> mutate(y = mean(x)) |> ungroup(), with the rows in their original order. The result is always ungrouped. Supplying.bywhen.datais already grouped (viagroup_by()) is an error, as in dplyr.- .keep
One of
"all"(default),"used","unused","none"; controls which of.data's other columns (besides ones...creates or modifies, and group columns, both of which are always kept) survive in the output – see ".keepsemantics" below.- .before, .after
Optionally, control where new columns should appear, using the same tidyselect syntax as
relocate.tbl_gpu(). Only new columns are moved; a modified existing column stays where it is.
Value
A tbl_gpu object with the new or modified columns. If a column
name already exists, it is replaced. New columns are appended (subject
to .before/.after), and .data's other columns are kept or dropped
per .keep.
Details
.keep semantics
As in dplyr, the columns created or modified by ... (every dot's output
column, new or replaced) and every grouping column are always kept,
whatever .keep says. .keep only controls which other (untouched,
non-grouping) columns of .data are kept alongside them:
"all"(default): every other column."used": other columns that are referenced as an input to any of...'s expressions (union across all dots)."unused": other columns not referenced as an input to any expression – the complement of"used"."none": no other columns at all.
Column order: .data's columns keep their order (modified columns don't
move), and new columns are appended at the end (or placed with
.before/.after); .keep then drops columns without changing that
order. This differs from transmute(), whose output order is
the literal ... dot order (see transmute()'s own docs).
Supported expressions
A function runs on the GPU only when its name, in the expression's
environment, is the base, dplyr or lubridate function itself: a
function of your own with the same name (local, in an enclosing function or
global) runs on the CPU, as dplyr would call it, and pkg::fn is the
function of that package. The same holds for a function passed as a value
(across(x, f), a list of functions held in a variable, !!f) and for the
functions and lambdas of the scoped verbs (mutate_at(), summarise_all(),
filter_if(), ...): one that is, or calls, a function of yours with the
name of a GPU function runs on the CPU. These run on the GPU:
Arithmetic:
+,-,*,/,^,%%,%/%, unary-, nested to any depth ((x + y) * z - 1), with a scalar on either side (mutate(y = 10 - x))Comparisons and logic:
==,!=,<,<=,>,>=,&,|,!,xor()– these produce a logical column, e.g.mutate(is_big = x > 100). Two strings compare with==,!=,%in%andbetween()on the GPU whatever the session's collation.<,<=,>and>=of strings compare bytes on the GPU, while R uses the session's collation, so they run on the GPU only whenSys.getlocale("LC_COLLATE")is"C"or"POSIX", and in dplyr on the CPU otherwise. A string compared with a number runs on the CPU (R compares them as strings).is.na(),is.nan(),between(x, lo, hi),near(x, y, tol = )(abs(x - y) < tol, asdplyr::near()defines it),%in%(including a bareNAon the right-hand side, e.g.x %in% NA, asNA %in% NAisTRUEin base R; an empty set is alwaysFALSE)Math functions:
sqrt(),log()(includinglog(x, base)),log2(),log10(),exp(),abs(),floor(),ceiling(),sin(),cos(),tan(),round(x)/round(x, digits)(banker's rounding, as in R)String functions, among them
nchar(),toupper(),tolower(),substr(),trimws(),startsWith(),endsWith();paste()andpaste0()when every argument is a string (a number or a logical argument runs on the CPU), with a constantsepand nocollapse; andgrepl(),sub()andgsub()with a constant pattern (ignore.case,perlanduseBytesrun on the CPU)Dates and date-times: a
Dateplus or minus a whole number of days, lubridate'syear(),month(),day(),hour(),minute(),second(),quarter(),yday(),wday(),floor_date(),ceiling_date()andround_date(), andas.Date()/as.POSIXct(), for the arguments the GPU supports; other forms run on the CPUA factor column compared with a label (
f == "a",f %in% c("a", "b"), and<,>, ... for an ordered factor), andas.character(),as.integer()oras.numeric()of a factor columnif_else(cond, yes, no, missing = NULL)– strict-but-promoting type unification acrossyes/no/missing(int/double/logical mix freely, like dplyr's vctrs-based common type;STRINGonly unifies withSTRING). AnNAcondition producesNA(ormissing, if supplied) in the output, as in dplyr (this is not the same as treating anNAcondition likeFALSE)case_when(cond1 ~ val1, cond2 ~ val2, ..., .default = val)– first-match-wins; anNAcondition is treated as no match (falls through to the next clause, or.default); unmatched rows become a typedNAwhen.defaultisn't supplied; the same value-type unification rule asif_else()applies across everyval_iplus.default. A call with.ptype=,.size=or.unmatched=runs on the CPU.coalesce(...)– first non-NA value per row, left to right, across any number of columns/scalars; same value-type unification rule asif_else()na_if(x, y)–xwithNAwhereverx == y; the output always keepsx's own type (unlikeif_else()/coalesce(),yis never promoted into the result, only compared against)case_match(.x, old_values ~ new_value, ..., .default = val)– matches.xby value against each clause's (possibly multi-element) left-hand side, first match wins;NAon a clause's left-hand side matches.x's ownNAelements (base R'sNA %in% NAisTRUE); unmatched rows become.default(typedNAif not supplied), with the same value-type unification rule ascase_when()across everynew_valueplus.default. dplyr 1.2 deprecates it in favor ofrecode_values()/replace_values(); it still runs on the GPU. A call with.ptype=runs on the CPU.recode(.x, old = new, ..., .default =, .missing =)– on the GPU only for a bare character/integer/double column.xand scalar literal replacements of one shared type (dplyr::recode, including!!!lookups); duplicate keys, factor.x,recode_factor(), and a result type different from.xwithout.defaultrun on the CPU.recode_values(x, old_values ~ new_value, ..., default = val)– the non-deprecated equivalent ofcase_match()above (the same semantics,defaultinstead of.default). Thefrom=/to=lookup-table form andunmatched=/ptype=run on the CPU.replace_values(x, old_values ~ new_value, ...)– likerecode_values(), but type stable: the output always keepsx's own type (everynew_valueis cast to it, never unified/promoted), and unmatched rows keep their originalxvalue (there is nodefault=). Thefrom=/to=form runs on the CPU.replace_when(x, cond1 ~ val1, cond2 ~ val2, ...)– likecase_when(), but with the type-stable, "unmatched rows keepx" behavior ofreplace_values()(anNAcondition is treated as no match, as incase_when())when_all(..., na_rm = FALSE)/when_any(..., na_rm = FALSE)– elementwise&/|generalized to any number of logical inputs (when_any(x, y, z)isx | y | z).na_rm = TRUEtreatsNAas each operator's identity element (FALSEforwhen_any(),TRUEforwhen_all()) rather than propagating it – e.g.when_any(NA, NA, na_rm = TRUE)isFALSE, notNA. A call withsize=runs on the CPU.Plain column copies (
mutate(y = x))A later dot in the same
mutate()call referencing an earlier dot's output column (mutate(a = x + y, b = a * 2)), also when it is a window function's output (mutate(a = cumsum(x), b = lag(a)))The
.data/.envpronouns, and ordinary R symbols (a bare name that matches a column resolves to that column; otherwise it is looked up as an R variable: columns shadow the environment, as in dplyr)Window functions, on ungrouped and grouped (
group_by()) tables, nested to any depth with any of the above (mutate(y = x - lag(x)),mutate(z = lag(cumsum(x))),mutate(centered = x - mean(x))):row_number()(sequential position) /row_number(x)(ranked position, ties broken by original position) – per-group undergroup_by()lag(x, n = 1, default = NA, order_by = NULL)/lead(...)– a shift that keeps the row order;order_by=(a bare column,desc(column), or-column) makes the shift follow that ordering instead of the table's/group's current row ordercumsum()/cummax()/cummin()/cumprod()– with R'sNApropagation (cumsum(c(1, 2, NA, 4))is1, 3, NA, NA: once an NA is seen, every later cumulative value in that group is NA too). Thecumsum()of an integer or logical is an integer that isNAfrom the first overflow on (with R's warning), as in Rcummean()(cumsum(x) / row_number(), accumulated in double),cumall()/cumany(), andconsecutive_id()of one column (a group id that increases whenever the value changes; adjacentNAs count as unchanged)min_rank()/dense_rank()/percent_rank()/cume_dist()– ties andNAas in dplyr (NAinput ->NArank;percent_rank()is(min_rank(x) - 1) / (n_non_NA - 1),NaNfor a group with exactly one non-NAvalue, as dplyr'sNaN, notNA;cume_dist()isrank(x, ties = "max") / n_non_NA)roll_mean(),roll_sum(),roll_min(),roll_max()androll_sd(), and data.table'sfrollmean(),frollsum(),frollmin(),frollmax()andfrollsd()with their defaultalign,fill,adaptive,partialandgive.names;roll_median()runs on the CPU.roll_min()/roll_max()of an integer, logical,DateorPOSIXctcolumn keep its type, where dplyr returns a doublemean()/sum()/min()/max()/n()/sd()/var()/median()/n_distinct()– one aggregate broadcast to every row of its group (or the whole table, ungrouped);mean()/sum()/min()/max()/sd()/var()/median()follow R'sna.rm = FALSEdefault (anyNAin the group makes that group's resultNA);n()always counts every row regardless ofNAs, andn_distinct()countsNAas a value.median()runs on the GPU for a double,DateorPOSIXctcolumn (of an integer or logical one, on the CPU), andmin()/max()of a string column under the collation rule of the comparisons above. On the GPU,mean()andmedian()of aDateare floored to whole days with acuplyr_warning_fractional_datewarning, where dplyr keeps the fractionalDate.sum()of an integer or logical is an integer, as in dplyr. When a sum leaves the integer range dplyr returns a double (for the whole column, and for any expression on it): the call is then rerun by dplyr on the CPU. A lazy table can't plan for that (the type depends on the data), so a lazymutate()with an integersum()runs at the verb like an eager one (a plan break first runs the pending steps) and returns a lazy table with nothing pending; a logicalsum()stays in the plan (it overflows only past 2^31TRUErows, with acuplyr_error_sum_overflowatcollect())first(x, order_by = NULL)/last(x, order_by = NULL)/nth(x, n, order_by = NULL)– the first/last/nth row of the group in its current row order, or inorder_by's order when supplied; negativencounts from the end (nth(x, -1)==last(x)); an out-of-rangengivesNA. A call withdefault=orna_rm=runs on the CPU.ntile(x = row_number(), n)order_by(order_by, call)/with_order(order_by, fun, x, ...)– as in dplyr, only the first argument ofcallis put inorder_by's order (stable,NAlast); the other arguments are evaluated in row order, and the call stays on the GPU only when each of them is a non-NULLscalar that reads no column. On the GPU: a window call wrapped directly (cumsum()/cummax()/cummin()/cumprod()/lag()/lead()/roll_*()exceptroll_median(), andcummean()/cumall()/cumany()/consecutive_id()), the rank functions that depend only on the values (min_rank(),dense_rank(), ... are unaffected by the order), and an elementwise call whose other arguments are scalars (order_by(o, cumsum(x) * 2)iscumsum(x) * 2: the window inside the first argument runs in row order, as in dplyr). Everything else runs the whole call on the CPU, which gives dplyr's value or error:roll_median(), an elementwise call with another column argument (order_by(o, cumsum(x) + lag(x))), aNULLor empty extra argument (lag(x, default = NULL)),row_number(x)/ntile(x, n)(ties broken by the order),first()/last()/nth(), aggregates, a nestedorder_by()as the wrapped call itself (order_by(o, order_by(i, cumsum(x))); nested inside the first argument it stays on the GPU), and shapes dplyr rejects (order_by(o, row_number()))
Every one of these is evaluated within each
group_by()group when.datais grouped, as in dplyr: the rows keep their order in the output (unlike groupedslice()).
Column replacement behavior
When the output column name matches an existing column, the existing
column is replaced in-place (preserving column order). For example,
mutate(x = x + 1) will modify x rather than creating a duplicate.
Result type (type promotion)
The output column's type follows from the operation and its inputs (the column types and, for a column-scalar expression, the R literal's own type), as in R:
A plain column copy (
mutate(y = x)) preserves the source column's type exactly.Arithmetic on a string column is an error, as in R. Arithmetic on a factor column runs in dplyr on the CPU (dplyr warns and gives
NA). ADateplus or minus a whole number of days stays on the GPU; other date and date-time arithmetic (t + 3600on aPOSIXct, the difference of two dates, ...) runs in dplyr on the CPU./and^always give a double, as in R (1L / 2Land2L ^ 2Lare both doubles).+,-,*,%%,%/%keep integers: the result is an integer when every input column and R literal involved is integer or logical (TRUE + TRUEis2L, as in R). Like R, an integer+,-or*whose result leaves.Machine$integer.maxisNAwith the warning "NAs produced by integer overflow" (once per call; atcollect()for a lazy table), and%/%/%%by0LareNA. If any input is a double, the result is a double; otherwise, if any input is an integer64, the result is an integer64. A bare R numeric literal (e.g. the1inmutate(y = int_col + 1)) is a double in R, so it makes the result a double – write1Lto keep an integer result.Comparisons, logic,
is.na(),between(),%in%all produce a logical column.sqrt(),log(),exp(),floor(),ceiling(),sin(),cos(),tan()always give a double, as in R (floor(1L)is a double), and so doesround()(typeof(round(1L))is also a double in R, unlikeabs()below).abs()preserves the argument's type, except a logical column, which becomes an integer (as in R:typeof(abs(TRUE))is"integer", not"logical").A bare
NA(untyped) is logical when it is an entire mutate expression by itself (mutate(y = NA), astypeof(NA)); as an operand inside an arithmetic expression (mutate(y = int_col + NA)) it takes the other operand's type (as in R:1L + NAis an integer, not a double). A typed NA literal (NA_real_,NA_integer_, ...) always keeps its own type.
Runs on the CPU
An expression that is not in the list above, or that uses a form the list
sends to the CPU, runs the whole mutate() call in dplyr on the CPU (set
options(cuplyr.fallback = "warn") to be told when; see
cuplyr-fallback). So does an argument type for which the GPU would not
give R's result, for example cummax() of a logical column, or sum(),
mean(), min() or max() of an integer64 column. Among the other
cases:
order_by()/with_order()with a general expression as the ordering argument (only a bare column,desc(column), or-columnis on the GPU, with-for numeric/logical columns anddesc()of a string only under a C collation:order_by(a + b, cumsum(x))runs on the CPU); see theorder_by()item above for what the wrapped call may be on the GPUconsecutive_id(a, b, ...)of more than one columnSliding-window functions other than the
roll_*()family (slider::slide_*()and similar)The arguments named in the items above:
case_when()'s andcase_match()'s.ptype=/.size=/.unmatched=,recode_values()'s andreplace_values()'sfrom=/to=andunmatched=/ptype=, andwhen_all()'s andwhen_any()'ssize=
See also
filter.tbl_gpu for filtering rows,
select.tbl_gpu for selecting columns,
collect.tbl_gpu for retrieving results
Examples
library(dplyr)
if (has_gpu()) {
gpu_mtcars <- tbl_gpu(mtcars)
# Add a new column
result <- gpu_mtcars |>
mutate(kpl = mpg * 0.425) |>
collect()
# Modify an existing column
adjusted <- gpu_mtcars |>
mutate(mpg = mpg + 5) |>
collect()
# Combine two columns
gpu_cars <- tbl_gpu(cars)
result <- gpu_cars |>
mutate(ratio = dist / speed) |>
collect()
# Chain multiple mutations
result <- gpu_mtcars |>
mutate(power_weight = hp / wt) |>
mutate(efficiency = mpg * power_weight) |>
collect()
}
