I am interested in the data.table
equivalent of using across()
to transform multiple columns and then return the whole dataset. I am able to use lapply()
on a subset of columns, but this only returns the selected columns as demonstrated below.
Just wondering if a simple solution to this problem can be found. I have also attached the intended solution using the dplyr
method. Thanks!
# Convert iris into data.table object
iris <- setDT(datasets::iris)
# Select columns containing "Petal"
petal_cols <- str_subset(colnames(iris), "Petal")
# Transform multiple columns
iris[,
lapply(.SD, round, digits = 0),
.SDcols = petal_cols]
# This does not work
# iris[,
# c("col1", "col2") := unlist(lapply(.SD, round, digits = 0), recursive = F),
# .SDcols = petal_cols]
# dplyr solution ---------------------------------------------------------------
iris %>%
mutate(across(contains("Petal"), ~round(.x, digits = 0)))
Note: I have read another post but the solution using c(cols) := unlist(lapply(...), recursive = FALSE) didn't work for me.