rrg rrg - 14 days ago 5
R Question

Generate an xts of numerics from .csv with some characters/"#N/A"

I enter a headed Excel CSV and examine with

str(returns.xts)
. The following code generates character values within the
xts
.

file <- "~/GCS/returns_Q216.csv"
returns_Q216_ <- read.csv(file=file)
returns <- read.zoo(data.frame(returns_Q216_), FUN = as.Date, format='%d/%m/%Y')
returns.xts <- as.xts(returns)


What is the best way to convert the xts contents to numeric from character whilst preserving xts (and date column)?

> `str(returns)`
An ‘xts’ object on 2007-01-31/2015-05-31 containing:
Data: `chr` [1:101, 1:18] "-0.002535663" "-0.001687755" "0.032882512" "0.024199512" "0.027812955" ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:18] "UK.EQUITY" "EUR.EQUITY" "NA.EQUITY" "ASIA.EQUITY" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
NULL
> returns[8,9]
PROPERTY
2007-08-31 "-4.25063E-05"


When I try
as.numeric(returns.xts)
I get a structure 1x1 cell without the date as row.

> str(as.numeric(returns))
num [1:1818] -0.00254 -0.00169 0.03288 0.0242 0.02781 ...

Answer

You should use the na.strings argument to read.csv (which can be passed via read.zoo), as I said in my answer to your previous question.

file <- "~/GCS/returns_Q216.csv"
returns <- read.zoo(file, FUN=as.Date, format='%d/%m/%Y', na.strings="#N/A")
returns.xts <- as.xts(returns)