首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用NAs将矩阵转换为时间序列

使用NAs将矩阵转换为时间序列
EN

Stack Overflow用户
提问于 2018-08-30 04:35:17
回答 1查看 25关注 0票数 0

我有一个数据框,第一行由货币名称组成,第二行由日期组成,渴望行由这些日期的历史价格组成。

如何将其转换为时间序列对象,该对象的列由不同的货币组成,行由这些日期的历史价格组成?问题是,在某些日子里,soem货币没有价格……我如何用NAs填充它们并自动将它们对齐?

EN

回答 1

Stack Overflow用户

发布于 2018-08-30 04:58:05

假设数据框名为crypto.market s.post.2108,收盘价为"symbol“、"dates”和"close“。

然后我会这样做:

代码语言:javascript
运行
复制
# Creates matrix whose columns are different crypto-currencies and whose rows are different times
#---------------------------------------------------------------------------------------------------#
# N Columns
Col.coins<-unique(crypto.markets.post.2018$symbol);N.coins<-length(Col.coins) # Counts the number of coins in recent history


# N Rows
Row.coins<-seq(from=min(dates),to=max(dates),by=1);N.Rows<-length(Row.coins)

# Initialize Matrix
historical.max.min<-historical.volum<-historical.prices<-matrix(NA,nrow = N.Rows,ncol=N.coins); rownames(historical.prices)<-Row.coins; colnames(historical.prices)<-Col.coins

# Writes data-frame of closing prices
for(j.coin in 1:N.coins){
  time.series.iteration<-crypto.markets.post.2018$symbol == Col.coins[j.coin]#Loads timeseries of this iteration
  time.series.iteration<-crypto.markets.post.2018[time.series.iteration,]
  N.NAs.needed.for.corecsion<-N.Rows-length(as.Date(time.series.iteration$date)) # Determines the difference between the data-size and the matrix's dimensions (for incomplete time-series only :D)
  # Historical Prices
  historical.prices[,j.coin]<-append(rep(NA,N.NAs.needed.for.corecsion),time.series.iteration$close) # Tags on the ts length
  # Historical Volum
  historical.volum[,j.coin]<-append(rep(NA,N.NAs.needed.for.corecsion),time.series.iteration$volume) # Tags on the ts length
  # Difference between max and min
  historical.max.min[,j.coin]<-append(rep(NA,N.NAs.needed.for.corecsion),((time.series.iteration$high)-(time.series.iteration$low))
                                ) # Tags on the ts length
}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52085697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档