转换data.table中的一组列

mba*_*ask 11 r data.table

一个data.table新手的问题.我想data.table通过对它们应用数学公式来转换a中的一组列.列集必须排除总列数中的一个或多个.

data.frame方面,我会做:

data(iris)
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

iris[, -5] <- iris[, -5] * 1e3
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1         5100        3500         1400         200  setosa
2         4900        3000         1400         200  setosa
3         4700        3200         1300         200  setosa
4         4600        3100         1500         200  setosa
5         5000        3600         1400         200  setosa
6         5400        3900         1700         400  setosa
Run Code Online (Sandbox Code Playgroud)

我知道如何选择多个列data.table:

iris.dt <- data.table(iris)
head(iris.dt[, -5, with = FALSE])
Run Code Online (Sandbox Code Playgroud)

甚至:

head(iris.dt[, !"Species", with = FALSE])
Run Code Online (Sandbox Code Playgroud)

如何利用data.tablepass-by-reference 实际转换所选列?

A5C*_*2T1 13

如何使用.SDCols参数以及reference(:=)赋值:

DT <- data.table(iris)
DT[, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
   :=lapply(.SD, function(x) x*1000), .SDcols=1:4]
# Alternatively you can grab the names the usual way:
# DT[, names(DT)[1:4] := lapply(.SD, function(x) x*1000), .SDcols=1:4]
DT
#      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#   1:         5100        3500         1400         200    setosa
#   2:         4900        3000         1400         200    setosa
#   3:         4700        3200         1300         200    setosa
#   4:         4600        3100         1500         200    setosa
#   5:         5000        3600         1400         200    setosa
#  ---                                                            
# 146:         6700        3000         5200        2300 virginica
# 147:         6300        2500         5000        1900 virginica
# 148:         6500        3000         5200        2000 virginica
# 149:         6200        3400         5400        2300 virginica
# 150:         5900        3000         5100        1800 virginica
Run Code Online (Sandbox Code Playgroud)


小智 6

.SDcols是正确的方法,但您可以使用向量仅指定一次列名称。

DT <- data.table(iris)
colnms <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
DT[, (colnms) := lapply(.SD, function(x) x*1000), .SDcols = colnms]
Run Code Online (Sandbox Code Playgroud)

请注意,您需要左侧的括号:=来停止data.table解释colnms为列名。