[R] Help with abs function

Nelson, Gary (MISC) gary.nelson at state.ma.us
Fri Jun 12 17:39:48 CEST 2015


I have come across some odd behavior (to me) using the abs() function that I wonder if anyone can explain.

Using  R version 3.2.0, I created a vector of absolute values using  the following code:

> tran<-c(7.2)
> tgrid<-c(7.1,7.4,7.3,7.1,7.3)
> dgrid<-abs(tgrid-tran)
> dgrid
[1] 0.1 0.2 0.1 0.1 0.1

When I tried to extract just the rows with values>0.1, I get

> dgrid[dgrid>0.1]
[1] 0.1 0.2 0.1

There should be only 1 value extracted.

However, if I enter the values by hand

> bgrid<-c(0.1,0.2,0.1,0.1,0.1)
> bgrid
[1] 0.1 0.2 0.1 0.1 0.1
> bgrid[bgrid>0.1]
[1] 0.2

The result is correct.  So why is this happening?

I did explore a little bit and found

> as.character(dgrid)
[1] "0.100000000000001"  "0.2"
[3] "0.0999999999999996" "0.100000000000001"
[5] "0.0999999999999996"

which shows the absolute values of the negative differences  are slightly greater than the difference of 0.1

Is this normal behavior for the abs() function?

Thanks,

Gary Nelson

	[[alternative HTML version deleted]]



More information about the R-help mailing list