在 R 中使用 data.table 转换多列和 return 所有列

Transform multiple columns and return all columns using data.table in R

我对 data.table 等效于使用 across() 转换多列然后 return 整个数据集 感兴趣。我可以在列的子集上使用 lapply(),但这仅 return 选定的列,如下所示。

只是想知道是否可以找到解决此问题的简单方法。我还使用 dplyr 方法附加了预期的解决方案。谢谢!

# 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)))

注意:我读过另一个post但是使用的解决方案对我不起作用。

lapply 的输出分配回 petal_cols

library(data.table)
iris[, (petal_cols) := lapply(.SD, round, digits = 0),.SDcols = petal_cols]
iris

#     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#  1:          5.1         3.5            1           0    setosa
#  2:          4.9         3.0            1           0    setosa
#  3:          4.7         3.2            1           0    setosa
#  4:          4.6         3.1            2           0    setosa
#  5:          5.0         3.6            1           0    setosa
# ---                                                            
#146:          6.7         3.0            5           2 virginica
#147:          6.3         2.5            5           2 virginica
#148:          6.5         3.0            5           2 virginica
#149:          6.2         3.4            5           2 virginica
#150:          5.9         3.0            5           2 virginica

使用dplyr

library(dplyr)
iris %>%
    mutate(across(all_of(petal_cols), ~ round(., digits = 0)))