R DF引用同一列中的2个不同行(返回)

时间:2014-02-15 04:30:33

标签: r dataframe calculated-columns stocks

我正在尝试在我的DF中创建一个名为“返回”的新列,但是我很难找到如何在同一列但不同的行中划分2个变量。

这是DF:

Date                  Open High  Low AdjClose  
2014-02-13 2014-02-13 1815 1830 1809     1830 
2014-02-12 2014-02-12 1820 1827 1816     1819 
2014-02-11 2014-02-11 1800 1824 1800     1820 
2014-02-10 2014-02-10 1796 1800 1792     1800 
2014-02-07 2014-02-07 1776 1798 1776     1797 
2014-02-06 2014-02-06 1753 1774 1753     1773

我假设代码看起来像这样:

SPXprices.df$Returns <- (SPXprices.df$AdjClose - SPXprices$AdjClose[x,x])/SPXprices$AdjClose[x,x]

我希望有人能在这里帮助我。

非常感谢任何见解!

2 个答案:

答案 0 :(得分:1)

这是你在找什么?

SPXprices.df <- read.table(header=T, text=
"
Date                  Open High  Low AdjClose  
2014-02-13 2014-02-13 1815 1830 1809     1830 
2014-02-12 2014-02-12 1820 1827 1816     1819 
2014-02-11 2014-02-11 1800 1824 1800     1820 
2014-02-10 2014-02-10 1796 1800 1792     1800 
2014-02-07 2014-02-07 1776 1798 1776     1797 
2014-02-06 2014-02-06 1753 1774 1753     1773
")

#sorting the data
SPXprices.df <- SPXprices.df[order(SPXprices.df$Date),]
#using lagpad from http://stackoverflow.com/a/13128713/2862090 to lag
lagpad <- function(x, k) {
  c(rep(NA, k), x)[1 : length(x)] 
}

#showing the result of lagpad
SPXprices.df$lagAdjClose <- lagpad(SPXprices.df$AdjClose,1)

#calculate returns
SPXprices.df$Returns <- (SPXprices.df$AdjClose - lagpad(SPXprices.df$AdjClose,1))/lagpad(SPXprices.df$AdjClose,1)

SPXprices.df
                Date Open High  Low AdjClose lagAdjClose       Returns
2014-02-06 2014-02-06 1753 1774 1753     1773          NA            NA
2014-02-07 2014-02-07 1776 1798 1776     1797        1773  0.0135363790
2014-02-10 2014-02-10 1796 1800 1792     1800        1797  0.0016694491
2014-02-11 2014-02-11 1800 1824 1800     1820        1800  0.0111111111
2014-02-12 2014-02-12 1820 1827 1816     1819        1820 -0.0005494505
2014-02-13 2014-02-13 1815 1830 1809     1830        1819  0.0060472787

答案 1 :(得分:1)

这是通过引用前一天来实现的方法

returns<-sapply(1:length(SPXprices.df$AdjClose), 
  FUN=function(x) (SPXprices.df$AdjClose[x] - SPXprices.df$AdjClose[x+1])/SPXprices.df$AdjClose[x+1])


SPXprices.df$Returns <- returns

sapply函数中,我使用SPXprices.df$AdjClose[x+1])

在第二天引用