如何在R中将data.frame转换为xts?

问题描述 投票:0回答:1

家伙!

我需要在数据框中使用函数Return.calculate(),但是首先要使用此函数,我需要将数据框转换为xts

这是我的数据框:

head(df)

     datas preco ticker empresa
1 20180102 32.09  BBAS3  BRASIL
2 20180103 33.10  BBAS3  BRASIL
3 20180104 33.52  BBAS3  BRASIL
4 20180105 33.70  BBAS3  BRASIL
5 20180108 33.64  BBAS3  BRASIL
6 20180109 33.59  BBAS3  BRASIL

[当我尝试使用as.xts()或xts()将数据帧转换为xts时,收到以下消息:

使用as.xts():

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

使用xts()

Error in xts(z) : order.by requires an appropriate time-based object

如何在xts对象中转换数据框?

非常感谢

r dataframe return transform xts
1个回答
1
投票

将第一列转换为Date对象并将其添加为rownames,然后使用as.xts

rownames(df) = as.Date(as.character(df$datas), "%Y%m%d")
xts::as.xts(df[-1])

或使用xts

xts::xts(df[-1], order.by = as.Date(as.character(df$datas), "%Y%m%d"))
© www.soinside.com 2019 - 2024. All rights reserved.