这是我想要计算的输出:
这是我在数据帧的每一行迭代并进行计算的代码,我知道这不是最好的方法
STOCKsbyQuarter_LOCF_Ticker <- subset(STOCKsbyQuarter_LOCF, STOCKsbyQuarter_LOCF$Ticker == input$STOCKTickers)
for( i in 1:length(STOCKsbyQuarter_LOCF_Ticker$ROIC)){
STOCKsbyQuarter_LOCF_Ticker$ROICDelta <- (STOCKsbyQuarter_LOCF_Ticker$ROIC[i+1] - STOCKsbyQuarter_LOCF_Ticker$ROIC[1]) /
(STOCKsbyQuarter_LOCF_Ticker$date[i+1] - STOCKsbyQuarter_LOCF_Ticker$date[1])
}
答案 0 :(得分:2)
df <- STOCKsbyQuarter_LOCF_Ticker
df$ROIC_Delta <- (df$ROIC - df$ROIC[1])/(df$Date - df$Date[1])
第一行的 ROIC_Delta
为NaN
。您可以用适当的值替换它。
答案 1 :(得分:1)
library(data.table)
dt = setDT(STOCKsbyQuarter_LOCF_Ticker)
dt[ , "ROIC Delta" := (ROIC - shift(ROIC))/as.numeric(difftime(Date, shift(Date),units = c("days")))]