如何在数据帧中进行逐行计算而不使用for循环 - R.

时间:2017-04-19 17:31:40

标签: r dt

这是我想要计算的输出:

Am trying to do the following ROICDelta Calculations

这是我在数据帧的每一行迭代并进行计算的代码,我知道这不是最好的方法

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

2 个答案:

答案 0 :(得分:2)

df <- STOCKsbyQuarter_LOCF_Ticker
df$ROIC_Delta <- (df$ROIC - df$ROIC[1])/(df$Date - df$Date[1])
第一行的

ROIC_DeltaNaN。您可以用适当的值替换它。

答案 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")))]