John L. Godlee
John L. Godlee

Reputation: 601

Remove doubles with no decimal places

I have a vector:

x <- c(0.0, 0.5, 1.000, 1.5, 1.6, 1.7, 1.75, 2.0, 2.4, 2.5, 3.0, 74.0)

How can I extract only the values of x which contain nonzero values after the decimal place? For example, the resultant vector would look like this:

c(0.5, 1.5, 1.6, 1.7, 1.75, 2.4, 2.5)

Which has removed 0.0, 1.000, 2.0, 3.0, and 74.0.

Upvotes: 5

Views: 116

Answers (2)

Andre Elrico
Andre Elrico

Reputation: 11500

alternatively

x[x %% 1 != 0]
#[1] 0.50 1.50 1.60 1.70 1.75 2.40 2.50

or

x[trunc(x) != x]
#[1] 0.50 1.50 1.60 1.70 1.75 2.40 2.50

or

x[as.integer(x) != x]
#[1] 0.50 1.50 1.60 1.70 1.75 2.40 2.50

or ( now I stop!)

x[grepl("\\.[^0]+$",x)]
#[1] 0.50 1.50 1.60 1.70 1.75 2.40 2.50

:D

Upvotes: 9

akrun
akrun

Reputation: 887991

We can construct a logical index with round

x[round(x) != x]
#[1] 0.50 1.50 1.60 1.70 1.75 2.40 2.50

Upvotes: 8

Related Questions