Steve
Steve

Reputation: 333

data.table, apply function to portion of a table

I want to apply function to portion of a table.

With data.frame, no problem:

df <- data.frame(name = paste("a", 1:10, sep = "-"),
                 x = 1:10,
                 y = rep(1:5),
                 z = rep(1:2, each = 5))

df[2:5, -1] <- scale(df[2:5, -1], center = c(1,2,3), scale = c(4,5,6))

But data.table complains:

dt <- data.table(name = paste("a", 1:10, sep = "-"),
                 x = 1:10,
                 y = rep(1:5),
                 z = rep(1:2, each = 5))


dt[2:5, -1] <- scale(dt[2:5, -1], center = c(1,2,3), scale = c(4,5,6))

Error in [<-.data.table(*tmp*, 2:5, -1, value = c(0.25, 0.5, 0.75, : Item 1 of column numbers in j is -1 which is outside range [1,ncol=4]. Use column names instead in j to add new columns.

What is the correct way in data.table? Thanks!

Upvotes: 0

Views: 54

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

data.table needs more work to apply scale :

library(data.table)

cols <- names(dt)[-1]
dt[, (cols) := lapply(.SD, as.numeric), .SDcols = cols]
dt[2:5, (cols) := Map(scale, .SD, c(1,2,3), c(4,5,6)), .SDcols = cols]

Upvotes: 0

Related Questions