Reputation: 4555
I am trying to replace the values of the vector with NA if the value == -273.17.
Here's a sample data:
x <- c(32,33,34,-273.17,32)
I would like to get this:
x <- c(32,33,34,NA,32)
Here's what I tried
x <- apply(x, 1,
(if (x==-273.17)
{x==NA} ))
But I get an error instead. Can anyone help me please?
Upvotes: 0
Views: 123
Reputation: 78
Boolean indexing, similar to answer from @Konrad.Rudolph, using tolerance based on default for ?all.equal
:
tol <- 0.5 * .Machine$double.eps # tolerance close to machine precision
float.equal <- function(a, b, p.tol = tol) { abs(a - b) < p.tol }
x[float.equal(x, -273.17)] <- NA
Consider the following if your requirement can be reduced to an easier-to-code predicate, e.g.:
x[x<0] <- NA
all.equal
works on vectors of equal length, and reports on the equality of full objects being compared, not element-wise equality.
For R version 3.0.1 (2013-05-16), isTRUE(all.equal())
does not produce the desired result:
> all.equal(x, -273.17)
[1] "Numeric: lengths (5, 1) differ"
> isTRUE(all.equal(x, -273.17))
[1] FALSE
Upvotes: 3
Reputation: 330083
You can use ifelse
ifelse(x==-273.17, NA, x)
but I like @KonradRudolph answer more.
Upvotes: 1
Reputation: 545588
You’d normally use subsetting for this:
x[x == -273.17] <- NA
However, beware of comparing floating point numbers in this fashion. all.equal
is a better alternative because it takes into account the inaccuracy in representation:
x[isTRUE(all.equal(x, -273.17))] <- NA
Upvotes: 2