1

我有一个 data.table 如下 -

library(data.table)
library(quantmod)
dataTableTemp <- getSymbols('AAPL', auto.assign = FALSE)
dt = data.table("date" = index(dataTableTemp), coredata(dataTableTemp))
> dt
            date  AAPL.Open  AAPL.High   AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
   1: 2007-01-03   3.081786   3.092143   2.925000   2.992857  1238319600      2.581790
   2: 2007-01-04   3.001786   3.069643   2.993571   3.059286   847260400      2.639095
   3: 2007-01-05   3.063214   3.078571   3.014286   3.037500   834741600      2.620301
   4: 2007-01-08   3.070000   3.090357   3.045714   3.052500   797106800      2.633241
   5: 2007-01-09   3.087500   3.320714   3.041071   3.306071  3349298400      2.851985
  ---                                                                                 
3542: 2021-01-27 143.429993 144.300003 140.410004 142.059998   140843800    142.059998
3543: 2021-01-28 139.520004 141.990005 136.699997 137.089996   142621100    137.089996
3544: 2021-01-29 135.830002 136.740005 130.210007 131.960007   177180600    131.960007
3545: 2021-02-01 133.750000 135.380005 130.929993 134.139999   106239800    134.139999
3546: 2021-02-02 135.729996 136.309998 134.610001 134.990005    82919600    134.990005

到这个data.table,我想添加TTR::ADX函数返回的几列

我尝试过类似以下的方法 -

dt[, c("DIp", "DIn", "DX", "ADX") := ADX(.SD, n = 14), .SDcols = c("AAPL.High", "AAPL.Low", "AAPL.Close")]

但是,我收到错误:

Error in `[.data.table`(x, , `:=`(c("DIp", "DIn", "DX", "ADX"), ADX(.SD,  : 
  Supplied 14184 items to be assigned to 3546 items of column 'DIp'.

期待有关如何解决此问题的建议。

谢谢。

4

1 回答 1

1

的输出ADX是一个matrix。我们可以将其转换为data.frameordata.table并且它应该可以工作

library(data.table)
dt[, c("DIp", "DIn", "DX", "ADX") := as.data.table(ADX(.SD, n = 14)), 
    .SDcols = c("AAPL.High", "AAPL.Low", "AAPL.Close")]

-输出

tail(dt)
         date AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted      DIp      DIn         DX      ADX
1: 2021-01-26    143.60    144.30   141.37     143.16    98390600        143.16 35.49876 13.80000 44.0148053 20.06051
2: 2021-01-27    143.43    144.30   140.41     142.06   140843800        142.06 33.04946 14.55058 38.8631656 21.40356
3: 2021-01-28    139.52    141.99   136.70     137.09   142621100        137.09 29.98002 19.62764 20.8685020 21.36534
4: 2021-01-29    135.83    136.74   130.21     131.96   177180600        131.96 26.56904 28.12707  2.8485164 20.04271
5: 2021-02-01    133.75    135.38   130.93     134.14   106239800        134.14 24.61803 26.06165  2.8485164 18.81455
6: 2021-02-02    135.73    136.31   134.61     134.99    82919600        134.99 25.29525 25.09397  0.3994657 17.49919
于 2021-02-03T18:16:52.997 回答