使用 lapply 在多个数据帧中查找单个平均值 - 错误的维数不正确 [英] Using lapply to find individual mean across multiple dataframes - error incorrect number of dimensions

查看:59
本文介绍了使用 lapply 在多个数据帧中查找单个平均值 - 错误的维数不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个包含以下形式的股票市场数据的数据框:

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

我有一个简单的函数来计算平均值并正确格式化.当我在单个股票(数据框)上运行它时,它会起作用.但是,当我尝试使用 lapply 将该函数应用于所有数据帧的列表时,出现错误:

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:

x[,Close] 中的错误:维数不正确.

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

symbols 是所有股票数据框的列表.

symbols is the list of all stock dataframes.

任何帮助将不胜感激.

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)

推荐答案

问题似乎是我正在获取运行移动平均线 (SMA) 的最后一个值(尾部),并在函数中添加名称 - 之前合并/合并数据帧.如果这一切都是在数据帧合并后完成的,那么它似乎可以工作.

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)

这篇关于使用 lapply 在多个数据帧中查找单个平均值 - 错误的维数不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆