Is it possible to update more than 1 column of a data.table in the same statement?
Something like
dt[,onecol:=1 anothercol:=2]
I've seen some examples where they do
dt[,c("onecol","anothercol"):=1]
but I don't know how to assign different formulas to each column
Yes, this has been possible since version 1.8.4:
library(data.table)
dt <- data.table(a=1:4, b=4:1)
dt[,c("a", "b") := list(min(a), max(b))]
# dt
# a b
# 1: 1 4
# 2: 1 4
# 3: 1 4
# 4: 1 4
Or, doing the same thing in a more readable way:
dt <- data.table(a=1:4, b=4:1)
dt[,`:=`(a = min(a),
b = max(a))]
dt
# a b
# 1: 1 4
# 2: 1 4
# 3: 1 4
# 4: 1 4
Search the current data.table NEWS file for "Multiple LHS" to see that this will also work with a by=
argument.
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