wwl wwl - 11 months ago 83
R Question

Creating new columns in data.table

I have several columns (literally) named A1, A2, A3, ... A50 in a data.table in R. Unfortunately, columns in my table are not arranged alphabetically.

I want to create a new column named sumA, which will contain A1 + A2 + ... + A50.

What's a simple (and not tedious) way of doing this?

Answer Source

Here is one option with Reduce and +

dt[, sumA := Reduce("+", .SD)]

If there are other columns i.e. columns other than 'A1:A50' in the dataset, use the .SDcols to specify the columns to select

dt[, sumA := Reduce("+", .SD), .SDcols = paste0("A", 1:50)]

Or as @Arun mentioned, if the columns are ordered, then : can be used to select the column

dt[, sumA := Reduce("+", .SD), .SDcols = A1:A50]