【问题标题】:Changing datatypes after converting from tibble to xts从 tibble 转换为 xts 后更改数据类型
【发布时间】:2021-10-09 21:12:35
【问题描述】:

我从网上抓取数据,并将其存储为具有以下数据类型的 tibble:

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%" ...

但是,一旦我将其更改为 xts

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

突然所有的数据都是字符...

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

我隐约意识到(或者至少我认为)xts 在百分比方面表现不佳;我该怎么做才能将所有内容一劳永逸地改回数字?

【问题讨论】:

    标签: r xts tibble


    【解决方案1】:

    xts不能存储混合类型的数据。由于Daily Return 列是字符,所有值都转换为字符。

    你有几个选择 -

    1. fund_table 中删除Daily Return 列。
    fund_table$`Daily Return` <- NULL
    
    1. Daily Return 转换为数字。
    fund_table$`Daily Return` <- readr::parse_number(fund_table$`Daily Return`)
    

    然后您可以像之前一样将数据转换为xts

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2020-09-14
      • 2011-05-16
      • 2018-11-22
      • 2017-04-21
      相关资源
      最近更新 更多