如何在r中的data.table中评估(或创建)即时列 [英] How can I evaluate (or create) an on the fly column in data.table in r

查看:160
本文介绍了如何在r中的data.table中评估(或创建)即时列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个新的data.table或者只是添加一些列到data.table。很容易指定多个新列,但如果我想要第三列根据我创建的列之一计算值,会发生什么。我认为plyr包可以做这样的事情。可以数据表吗?我确定我已经阅读过这个地方。

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 data.table? I am sure I have read about this somewhere

我想做如下:

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)]


推荐答案

也可以使用< - code> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆