Search code examples
rxtstibble

Changing datatypes after converting from tibble to xts


I scraped data from online, and it's stored as a tibble with the following data types:

tibble [40 x 4] (S3: tbl_df/tbl/data.frame)
 $ Date                   : Date[1:40], format: "2021-02-10" "2021-02-09" "2021-02-08" ...
 $ Net Asset Value        : num [1:40] 5.81 5.69 5.57 5.49 5.48 ...
 $ Accumulated Asset Value: num [1:40] 2.33 2.28 2.24 2.21 2.2 ...
 $ Daily Return           : chr [1:40] "2.15%" "2.18%" "1.46%" "0.18%" ...

However, once I change it to an xts

fund_table$Date <- as.Date(fund_table$Date,"%Y-%m-%d")
fund_table_xts <- xts(fund_table[,-1],  order.by = fund_table$Date)

Suddenly all the data are characters...

An ‘xts’ object on 2020-12-16/2021-02-10 containing:
    Data: chr [1:40, 1:3] ...

I'm vaguely aware (or at least I think) that xts doesn't do well with percentages; what do I do to change everything back to numbers once and for all?


Solution

  • xts cannot store data of mixed types. Since Daily Return column is character all the values are turned to characters.

    You have couple of options -

    1. Remove Daily Return column from fund_table.
    fund_table$`Daily Return` <- NULL
    
    1. Convert Daily Return to numeric.
    fund_table$`Daily Return` <- readr::parse_number(fund_table$`Daily Return`)
    

    Then you can convert the data to xts as you have done previously.