Skip to content

This is a method for the dplyr mutate() generic. It is translated to the j argument of [.data.table, using := to modify "in place". If .before or .after is provided, the new columns are relocated with a call to data.table::setcolorder().

Usage

# S3 method for dtplyr_step
mutate(.data, ..., .before = NULL, .after = NULL)

Arguments

.data

A lazy_dt().

...

<data-masking> Name-value pairs. The name gives the name of the column in the output, and the value should evaluate to a vector.

.before, .after

[Experimental] <tidy-select> Optionally, control where new columns should appear (the default is to add to the right hand side). See relocate() for more details.

Examples

library(dplyr, warn.conflicts = FALSE)

dt <- lazy_dt(data.frame(x = 1:5, y = 5:1))
dt %>%
  mutate(a = (x + y) / 2, b = sqrt(x^2 + y^2))
#> Source: local data table [5 x 4]
#> Call:   copy(`_DT23`)[, `:=`(a = (x + y)/2, b = sqrt(x^2 + y^2))]
#> 
#>       x     y     a     b
#>   <int> <int> <dbl> <dbl>
#> 1     1     5     3  5.10
#> 2     2     4     3  4.47
#> 3     3     3     3  4.24
#> 4     4     2     3  4.47
#> 5     5     1     3  5.10
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

# It uses a more sophisticated translation when newly created variables
# are used in the same expression
dt %>%
  mutate(x1 = x + 1, x2 = x1 + 1)
#> Source: local data table [5 x 4]
#> Call:   copy(`_DT23`)[, `:=`(c("x1", "x2"), {
#>     x1 <- x + 1
#>     x2 <- x1 + 1
#>     .(x1, x2)
#> })]
#> 
#>       x     y    x1    x2
#>   <int> <int> <dbl> <dbl>
#> 1     1     5     2     3
#> 2     2     4     3     4
#> 3     3     3     4     5
#> 4     4     2     5     6
#> 5     5     1     6     7
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results