Reputation: 15002
I have an xts
object (df
):
## a b
## 2015-09-14 -0.5470 NA
## 2015-09-15 0.0112 NA
## 2015-09-16 0.0910 0.932
## 2015-09-17 -Inf 0.862
## 2015-09-18 Inf 1.946
## 2015-09-21 -0.7050 2.692
## 2015-09-22 NaN 2.011
## 2015-09-23 -0.5440 1.859
## .
## .
## etc
Because column a
includes Inf
, -Inf
and NaN
, I am getting some errors. Is there a way to replace these values with NA
(to treat Inf
and NaN
as missing values)?
Upvotes: 1
Views: 4697
Reputation: 27408
You can use apply
, like you might on an ordinary matrix
Using the data that you provided:
d <- xts(read.zoo(text='date a b
2015-09-14 -0.5470 NA
2015-09-15 0.0112 NA
2015-09-16 0.0910 0.932
2015-09-17 -Inf 0.862
2015-09-18 Inf 1.946
2015-09-21 -0.7050 2.692
2015-09-22 NaN 2.011
2015-09-23 -0.5440 1.859', header=T, index=1))
apply(d, 2, function(x) ifelse(is.finite(x), x, NA))
## a b
## 2015-09-14 -0.5470 NA
## 2015-09-15 0.0112 NA
## 2015-09-16 0.0910 0.932
## 2015-09-17 NA 0.862
## 2015-09-18 NA 1.946
## 2015-09-21 -0.7050 2.692
## 2015-09-22 NA 2.011
## 2015-09-23 -0.5440 1.859
An alternative approach is to make the replacement by indexing the elements to keep (or remove)
d[!is.finite(d)] <- NA
Upvotes: 4