Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

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

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)]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...