I'm looking to add a column to a data.table
which is a concatenation of several other columns, the names of which I've stored in a vector cols
. Per https://stackoverflow.com/a/21682545/1840471 I tried do.call
+ paste
but couldn't get it working. Here's what I've tried:
# Using mtcars as example, e.g. first record should be "110 21 6"
dt <- data.table(mtcars)
cols <- c("hp", "mpg", "cyl")
# Works old-fashioned way
dt[, slice.verify := paste(hp, mpg, cyl)]
# Raw do.call+paste fails with message:
# Error in do.call(paste, cols): second argument must be a list
dt[, slice := do.call(paste, cols)]
# Making cols a list makes the column "hpmpgcyl" for each row
dt[, slice := do.call(paste, as.list(cols))]
# Applying get fails with message:
# Error in (function (x) : unused arguments ("mpg", "cyl")
dt[, slice := do.call(function(x) paste(get(x)), as.list(cols))]
Help appreciated - thanks.
Similar questions:
Concatenate columns and add them to beginning of Data Frame (operates on data.frames
using cbind
and do.call
- this was very slow on my data.table
)
R - concatenate row-wise across specific columns of dataframe (doesn't deal with columns as names or large number of columns)
Accessing columns in data.table using a character vector of column names (considers aggregation using column names)
We can use mget
to return the values of elements in 'cols' as a list
dt[, slice := do.call(paste, mget(cols))]
head(dt, 2)
# mpg cyl disp hp drat wt qsec vs am gear carb slice
#1: 21 6 160 110 3.9 2.620 16.46 0 1 4 4 110 21 6
#2: 21 6 160 110 3.9 2.875 17.02 0 1 4 4 110 21 6
Or another option is to specify the 'cols' in .SDcols
and paste
the .SD
dt[, slice:= do.call(paste, .SD), .SDcols = cols]
head(dt, 2)
# mpg cyl disp hp drat wt qsec vs am gear carb slice
#1: 21 6 160 110 3.9 2.620 16.46 0 1 4 4 110 21 6
#2: 21 6 160 110 3.9 2.875 17.02 0 1 4 4 110 21 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With