从 tibble 转换为 xts 后更改数据类型
Changing datatypes after converting from tibble to xts
我从网上抓取数据,并将其存储为具有以下数据类型的 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 在百分比方面表现不佳;我该怎么做才能一劳永逸地将所有内容改回数字?
xts
不能存储混合类型的数据。由于 Daily Return
列是字符,所有值都转换为字符。
你有两个选择 -
- 从
fund_table
中删除 Daily Return
列。
fund_table$`Daily Return` <- NULL
- 将
Daily Return
转换为数字。
fund_table$`Daily Return` <- readr::parse_number(fund_table$`Daily Return`)
然后您可以像之前一样将数据转换为 xts
。
我从网上抓取数据,并将其存储为具有以下数据类型的 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 在百分比方面表现不佳;我该怎么做才能一劳永逸地将所有内容改回数字?
xts
不能存储混合类型的数据。由于 Daily Return
列是字符,所有值都转换为字符。
你有两个选择 -
- 从
fund_table
中删除Daily Return
列。
fund_table$`Daily Return` <- NULL
- 将
Daily Return
转换为数字。
fund_table$`Daily Return` <- readr::parse_number(fund_table$`Daily Return`)
然后您可以像之前一样将数据转换为 xts
。