Washington Muniz
Washington Muniz

Reputation: 100

How to convert a data.frame to a xts in R?

guys!

I need to use the function Return.calculate(), in my dataframe, but to use this function, first of all, I need to convert my dataframe to xts.

This is my dataframe:

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

When I try to convert my dataframe to xts using as.xts() or xts() I receive the following messages:

using as.xts():

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

using xts()

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

What can I do to transform my dataframe in a xts object?

Many thanks

Upvotes: 1

Views: 1202

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388897

Convert first column to Date object and add it as rownames and then use as.xts

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

Or using xts

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

Upvotes: 1

Related Questions