使用rollmeanr将列添加到数据表

时间:2016-06-02 21:08:08

标签: r data.table

我正在尝试将“calc”列添加到下面的数据表中。对于每个mA#列,应该有一个Calc#列,即log(值/ MA#)​​

library(data.table)
library(zoo)
library(TTR)
date = seq(as.Date("2016-01-01"),as.Date("2016-01-10"),"day")
value =c(1,2,3,4,5,6,7,8,9,10)
mydata = data.frame (date, value)
setDT(mydata)[, paste0('MA',2:9) := lapply(2:9, function(x) rollmeanr(value, x, fill = rep(NA,x-1)) ),][]
setDT(mydata)[, paste0('Calc',2:9) := lapply(3:10, function(x)  log(value/mydata[,x])    ),][] # how do I add this column which is the value column/ each MA# column

1 个答案:

答案 0 :(得分:1)

my comment to your previous question翻译成答案:

setDT(mydata)[, paste0('Calc',2:9) := lapply(.SD, function(x) log(value/x)), .SDcols = 3:10][]

给出:

          date value MA2 MA3 MA4 MA5 MA6 MA7 MA8 MA9      Calc2     Calc3     Calc4     Calc5     Calc6     Calc7     Calc8     Calc9
 1: 2016-01-01     1  NA  NA  NA  NA  NA  NA  NA  NA         NA        NA        NA        NA        NA        NA        NA        NA
 2: 2016-01-02     2 1.5  NA  NA  NA  NA  NA  NA  NA 0.28768207        NA        NA        NA        NA        NA        NA        NA
 3: 2016-01-03     3 2.5   2  NA  NA  NA  NA  NA  NA 0.18232156 0.4054651        NA        NA        NA        NA        NA        NA
 4: 2016-01-04     4 3.5   3 2.5  NA  NA  NA  NA  NA 0.13353139 0.2876821 0.4700036        NA        NA        NA        NA        NA
 5: 2016-01-05     5 4.5   4 3.5   3  NA  NA  NA  NA 0.10536052 0.2231436 0.3566749 0.5108256        NA        NA        NA        NA
 6: 2016-01-06     6 5.5   5 4.5   4 3.5  NA  NA  NA 0.08701138 0.1823216 0.2876821 0.4054651 0.5389965        NA        NA        NA
 7: 2016-01-07     7 6.5   6 5.5   5 4.5   4  NA  NA 0.07410797 0.1541507 0.2411621 0.3364722 0.4418328 0.5596158        NA        NA
 8: 2016-01-08     8 7.5   7 6.5   6 5.5   5 4.5  NA 0.06453852 0.1335314 0.2076394 0.2876821 0.3746934 0.4700036 0.5753641        NA
 9: 2016-01-09     9 8.5   8 7.5   7 6.5   6 5.5   5 0.05715841 0.1177830 0.1823216 0.2513144 0.3254224 0.4054651 0.4924765 0.5877867
10: 2016-01-10    10 9.5   9 8.5   8 7.5   7 6.5   6 0.05129329 0.1053605 0.1625189 0.2231436 0.2876821 0.3566749 0.4307829 0.5108256