Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I evaluate (or create) an on the fly column in data.table in r

Tags:

r

data.table

I want to create a new data.table or maybe just add some columns to a data.table. It is easy to specify multiple new columns but what happens if I want a third column to calculate a value based on one of the columns I am creating. I think plyr package can do something such as that. Can we perform such iterative (sequential) column creation in data.table?

I want to do as follows

dt <- data.table(shop = 1:10, income = 10:19*70)
dt[ , list(hope = income * 1.05, hopemore = income * 1.20, hopemorerealistic = hopemore - 100)]  

or maybe

dt[ , `:=`(hope = income*1.05, hopemore = income*1.20, hopemorerealistic = hopemore-100)]
like image 880
Farrel Avatar asked Mar 29 '13 23:03

Farrel


2 Answers

You can also use <- within the call to list eg

DT <- data.table(a=1:5)


DT[, c('b','d') := list(b1 <- a*2, b1*3)]
DT
   a  b  d
1: 1  2  6
2: 2  4 12
3: 3  6 18
4: 4  8 24
5: 5 10 30

Or

DT[, `:=`(hope = hope <- a+1, z = hope-1)]
DT
   a  b  d hope z
1: 1  2  6    2 1
2: 2  4 12    3 2
3: 3  6 18    4 3
4: 4  8 24    5 4
5: 5 10 30    6 5
like image 107
mnel Avatar answered Oct 20 '22 00:10

mnel


It is possible by using curly braces and semicolons in j There are multiple ways to go about it, here are two examples:

# If you simply want to output: 

dt[ ,
  {hope=income*1.05;
   hopemore=income*1.20;
   list(hope=hope, hopemore=hopemore, hopemorerealistic=hopemore-100)}
]


# if you want to save the values

dt[ , c("hope", "hopemore", "hopemorerealistic")  := 
  {hope=income*1.05;
   hopemore=income*1.20;
   list(hope, hopemore, hopemore-100)}
]
dt
#     shop income   hope hopemore hopemorerealistic
#  1:    1    700  735.0      840               740
#  2:    2    770  808.5      924               824
#  3:    3    840  882.0     1008               908
#  4:    4    910  955.5     1092               992
#  5:    5    980 1029.0     1176              1076
#  6:    6   1050 1102.5     1260              1160
#  7:    7   1120 1176.0     1344              1244
#  8:    8   1190 1249.5     1428              1328
#  9:    9   1260 1323.0     1512              1412
# 10:   10   1330 1396.5     1596              1496
like image 43
Ricardo Saporta Avatar answered Oct 19 '22 22:10

Ricardo Saporta