gpt4 book ai didi

r - 是否可以将功能对象作为元素

转载 作者:行者123 更新时间:2023-12-04 13:31:18 24 4
gpt4 key购买 nike

简短答案:是,请参阅已接受的回复。

我下面有两个data.table

stocks = data.table(Ticker = c('xx','xx','yy','yy'), Date = c(as.IDate("2000-01-01"), as.IDate("2000-01-02")), t = c(1.8, 3.5))
Ticker Date t
1: xx 2000-01-01 1.8
2: xx 2000-01-02 3.5
3: yy 2000-01-01 1.8
4: yy 2000-01-02 3.5
tt = data.table(Date = c(as.IDate("2000-01-01"), as.IDate("2000-01-02")), t0 = c(1,2), t1 = c(2,3), t2 = c(3,4), y0 = c(10, 20), y1 = c(-20, -30), y2 = c(33,44))
Date t0 t1 t2 y0 y1 y2
1: 2000-01-01 1 2 3 10 -20 33
2: 2000-01-02 2 3 4 20 -30 44

对于 stocks中的每一行,我想根据 y中值的线性插值找到给定 t的近似 tt
zz = tt[stocks, on = 'Date']
zz[, y.approx := approx(c(t0,t1,t2), c(y0,y1,y2), t)$y, by = 'Date,Ticker']
Date t0 t1 t2 y0 y1 y2 Ticker t y.approx
1: 2000-01-01 1 2 3 10 -20 33 xx 1.8 -14
2: 2000-01-02 2 3 4 20 -30 44 xx 3.5 7
3: 2000-01-01 1 2 3 10 -20 33 yy 1.8 -14
4: 2000-01-02 2 3 4 20 -30 44 yy 3.5 7

问题在于,这样做有很多重复的计算。理想情况下,我想为每天定义一个 approxfun并将其应用于 stocks中的每一行。但是数据表不能将函数对象作为其元素。
tt[, ff := approxfun(c(t0,t1,t2), c(y0,y1,y2)), by = Date]
Error in `[.data.table`(tt, , `:=`(ff, approxfun(c(t0, t1, t2), c(y0, :
j evaluates to type 'closure'. Must evaluate to atomic vector or list.

我的问题是:
  • 是否有比在每一行上执行approx更好的方法(而且速度很慢)?
  • 数据表是否可以将函数对象作为其元素?
  • 最佳答案

    将函数存储在data.table中非常容易-您只需将它们放在列表中:

    tt[, ff := .(list(approxfun(c(t0,t1,t2), c(y0,y1,y2)))), by = Date]
    # Date t0 t1 t2 y0 y1 y2 ff
    #1: 2000-01-01 1 2 3 10 -20 33 <function>
    #2: 2000-01-02 2 3 4 20 -30 44 <function>

    stocks[tt, y.approx := ff[[1]](t), on = 'Date', by = .EACHI]
    stocks
    # Ticker Date t y.approx
    #1: xx 2000-01-01 1.8 -14
    #2: xx 2000-01-02 3.5 7
    #3: yy 2000-01-01 1.8 -14
    #4: yy 2000-01-02 3.5 7

    关于r - 是否可以将功能对象作为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36570702/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com