如何在 r 中的 data.table 中评估(或创建)动态列 [英] How can I evaluate (or create) an on the fly column in data.table in r
本文介绍了如何在 r 中的 data.table 中评估(或创建)动态列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个新的 data.table,或者只是向 data.table 添加一些列.指定多个新列很容易,但是如果我想要第三列根据我正在创建的列之一计算值会发生什么.我认为 plyr 包可以做这样的事情.我们可以在 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?
我想做如下
dt <- data.table(shop = 1:10, income = 10:19*70)
dt[ , list(hope = income * 1.05, hopemore = income * 1.20, hopemorerealistic = hopemore - 100)]
或许
dt[ , `:=`(hope = income*1.05, hopemore = income*1.20, hopemorerealistic = hopemore-100)]
推荐答案
你也可以在 list
的调用中使用 <-
例如
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
或者
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
这篇关于如何在 r 中的 data.table 中评估(或创建)动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文