我有一个1500 obs的df。和100个变量。 这些是股票,我想计算所有100股的EMA50,并将它们放入新的df中。我想将其放在一个循环中,因为在此之后我想绘制每个份额+结果。但是目前该情节并不重要。为了更好地展示整个过程,我举了一个例子:(也许有一种更简单的方法来编写此示例,但是我正处于学习的中间,仍在学习用R编写代码。)
library(tidyverse)
library(quantmod)
library(fPortfolio)
library(PerformanceAnalytics)
#
DStart <- "2016-01-01"
DEnd <- "2020-12-31"
#
#loading DAX and MDAX Index data from Yahoo Finance
TSLA <- getSymbols("TSLA", src="yahoo", from=DStart, to=DEnd, auto.assign=FALSE)
AAPL <- getSymbols("AAPL", src="yahoo", from=DStart, to=DEnd, auto.assign=FALSE)
AMZN <- getSymbols("AMZN", src="yahoo", from=DStart, to=DEnd, auto.assign=FALSE)
#
Closing <- merge(TSLA, AAPL, AMZN)
#
write.zoo(Closing, file="Closing.csv", sep=",", dec="." )
#
df_Closing <- Closing[,-c(1,2,3,5,6,7,8,9,11,12,13,14,15,17,18)]
我现在像我实际的df一样拥有df中的所有收盘价。 对于EMA的单独计算,我使用:
df_Closing$TSLA_EMA50 = EMA(df_Closing$TSLA.Close,50)
在搜索过程中,我遇到了几种解决方案,直到现在所有这些解决方案都以错误消息结尾。 我最近的尝试是这样的:
df_EMA50 <- df_Closing
for (i in names(df_Closing)) {
j <- EMA(df_Closing$i,50)
new_df[i] <- j$EMA50
}
答案 0 :(得分:1)
通常更容易按位置而不是按名称进行迭代。应该将输出data.frame
初始化为空,以便更容易发现问题并确保预期的输出。
df_EMA50 <- df_Closing[0, ]
for (i in seq_len(ncol(df_Closing))) {
j <- EMA(df_Closing[, i], 50)
colnames(j) <- colnames(df_Closing[, i])
df_EMA50 <- cbind(df_EMA50, j)
}