Can I asked why you want it chained "like a pipe" absolutely ?
As data.table is working by reference, there is no assignment and it is like it is chained by default without any pipe-like operator. Pipe operators are a way to chain operation without making an assignment.
library(data.table)
iris_dt <- as.data.table(iris)
iris_dt[, is.SETOSA := Species == "setosa"]
setnames(iris_dt, "is.SETOSA", "is_setosa")
iris_dt
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species is_setosa
#> 1: 5.1 3.5 1.4 0.2 setosa TRUE
#> 2: 4.9 3.0 1.4 0.2 setosa TRUE
#> 3: 4.7 3.2 1.3 0.2 setosa TRUE
#> 4: 4.6 3.1 1.5 0.2 setosa TRUE
#> 5: 5.0 3.6 1.4 0.2 setosa TRUE
#> ---
#> 146: 6.7 3.0 5.2 2.3 virginica FALSE
#> 147: 6.3 2.5 5.0 1.9 virginica FALSE
#> 148: 6.5 3.0 5.2 2.0 virginica FALSE
#> 149: 6.2 3.4 5.4 2.3 virginica FALSE
#> 150: 5.9 3.0 5.1 1.8 virginica FALSE
You can "pipe" it using the :=
operator using one of the multiple column syntax to create a new column with a new name then deleting the old one.
library(data.table)
iris_dt <- as.data.table(iris)
iris_dt[, is.SETOSA := Species == "setosa"][
, `:=`(is_setosa = is.SETOSA, is.SETOSA = NULL)]
names(iris_dt)
#> [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
#> [5] "Species" "is_setosa"
Otherwise, like mentioned in a previous post, using the %>%
pipe should work with setnames
but you may have difficulties to continue the chain without %>%
library(data.table)
library(magrittr)
iris_dt <- as.data.table(iris)
iris_dt[, is.SETOSA := Species == "setosa"] %>%
setnames(., "is.SETOSA", "is_setosa")
names(iris_dt)
#> [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
#> [5] "Species" "is_setosa"