Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update more than one column of a data.table

Tags:

r

data.table

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

like image 505
Juancentro Avatar asked Dec 18 '12 19:12

Juancentro


1 Answers

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.

like image 152
Josh O'Brien Avatar answered Oct 28 '22 22:10

Josh O'Brien