Using lapply to find individual mean across multiple dataframes - error incorrect number of dimensions

一笑奈何 提交于 2019-12-11 13:32:27

问题


I have multiple dataframes that contain stock market data in the form:

Open High Low Close Volume

I am trying to get an average (over a given period) of the last row of each stock and combine them into a single data frame like so:

Name SMA
StockA 15.1
StockB 34.44

I have a simple function that calculates the mean value and formats it correctly. It works on when I run it on a single stock (dataframe). However when I try and use lapply to apply the function to a list of all the dataframes, I get the error:

Error in x[,Close]: incorrect number of dimensions.

symbols is the list of all stock dataframes.

Any help would be greatly appreciated.

require(TTR)
require(quantmod)

symbols <- c("XLF", "XLK", "XLU", "XLE", "XLP", "XLF", "XLB", "XLV", "XLY")
getSymbols(symbols, src='yahoo', from = '2016-01-01')

fun1<-function(x,Close) {
  mean1<-SMA(x[,Close],5)
  mean2<-tail(mean1,1)
  df_name<-deparse(substitute(x))
  print(mean2,paste(df_name))
}

df<-lapply(symbols,fun1)
final_df <- do.call(rbind, df)

回答1:


The issue appeared to be that I was taking the last value (tail) of the running moving average (SMA) and also adding names within the function - prior to combining/merging the data frames. If this is all done after the dataframes have been merged, then it seems to work.

require(TTR)
require(quantmod)

symbols <- c("XLF", "XLK", "XLU", "XLE", "XLP", "XLF", "XLB", "XLV", "XLY")

StartDate = '2016-01-01'

Stocks = lapply(symbols, function(sym, column) {
  SMA(na.omit(getSymbols(sym, from=StartDate, auto.assign=FALSE))[,4],5)
})

test<-do.call(merge, Stocks)
test2<-tail(test,1)
test3<-t(test2)
rownames(test3)<-symbols
colnames(test3)<-"SMA"
View(test3)


来源:https://stackoverflow.com/questions/37290727/using-lapply-to-find-individual-mean-across-multiple-dataframes-error-incorrec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!