通过划分旧列,同时创建多个新的data.table列

时间:2015-12-11 10:07:27

标签: r data.table

在data.table中有更好的方法吗?

library(data.table)

n_obs <- 10
df <- data.frame(y=rnorm(n_obs), x1=runif(n_obs, 0, 1000), x2=runif(n_obs, 0, 1000),
                 x3=runif(n_obs, -1000, 1000), x4=runif(n_obs, -1000, 1000))
colnames <- c("x1", "x2", "x3", "x4")
colnames_scaled <- sprintf("%s_scaled", colnames)
df[, colnames_scaled] <- df[, colnames] / 1000  # Create four new columns in one line
all(colnames_scaled %in% names(df))  # True
max(df[, colnames_scaled]) <= 1  # True

## What's the right way to do the same thing with data.table?
dt <- data.table(y=rnorm(n_obs), x1=runif(n_obs, 0, 1000), x2=runif(n_obs, 0, 1000),
                 x3=runif(n_obs, -1000, 1000), x4=runif(n_obs, -1000, 1000))
for(i in seq_along(colnames)) {
    dt[[colnames_scaled[i]]] <- dt[[colnames[i]]] / 1000
}
all(colnames_scaled %in% names(dt))  # True
max(dt[, colnames_scaled, with=F]) <= 1  # True

1 个答案:

答案 0 :(得分:4)

你可以这样做:

dt[, paste(names(dt)[-1], "scaled", sep="_") := lapply(.SD, `/`, 1000), .SDcols=names(dt)[-1]]

或者,使用你的向量colnames(实际上应该使用除R“保留”名称以外的其他名称命名;-))和colnames_scaled

dt[, (colnames_scaled) := lapply(.SD, `/`, 1000), .SDcols = colnames]

检查:

all(colnames_scaled %in% names(dt))
#[1] TRUE
max(dt[, colnames_scaled, with=F]) <= 1
#[1] TRUE