1

I ran in a very strange problem I don't know how to solve and have never seen. I can subset a data.frame for some but not for other numeric values.

Here is the data I use:

library(dplyr)
ws <- seq(0, 1, by=.1)
kombos <- expand.grid(weightjaw2 = ws,
                  weightjaw3 = ws) %>% as.data.frame
kombos$kombi <- 1:nrow(kombos)
kombos$weightjaw2 <- as.numeric(kombos$weightjaw2)
kombos$weightjaw3 <- as.numeric(kombos$weightjaw3)
class(kombos$weightjaw2)

[1] "numeric"

Now, I need to subset this data.frame. This works well, say for example, the value 0.1.

kombos %>% filter(weightjaw2==0.1)
   weightjaw2 weightjaw3 kombi
1         0.1        0.0     2
2         0.1        0.1    13
3         0.1        0.2    24
4         0.1        0.3    35
5         0.1        0.4    46
6         0.1        0.5    57
7         0.1        0.6    68
8         0.1        0.7    79
9         0.1        0.8    90
10        0.1        0.9   101
11        0.1        1.0   112

Strangely enough, this does not work for values of 0.3, 0.6, and 0.7.

kombos %>% filter(weightjaw2==0.3)
[1] weightjaw2 weightjaw3 kombi     
<0 rows> (or 0-length row.names)

The same holds for subset(kombos, weightjaw2==0.3). Why is that and how can I solve this?

EDIT

I solved this using dyplyr::near():

kombos %>% filter(near(weightjaw2, 0.3))
Thomas
  • 1,392
  • 3
  • 22
  • 38
  • It would be a floating point issue You can check the difference `kombos$weightjaw2 - 0.3` – akrun Jan 24 '20 at 21:51
  • 2
    Duplicate of [Why are these numbers not equal?](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) – M-- Jan 24 '20 at 21:58
  • One option is to `filter` after converitng to `character` `kombos %>% filter(as.character(weightjaw2) == 0.3)` – akrun Jan 24 '20 at 22:01

1 Answers1

0

The == requires both lhs and rhs to be exactly equal. The 'weightjaw2' column is not exactly equal to 0.3 due to the precision checks. One option is to convert the column to character in filter to subset the rows

library(dplyr)
kombos %>%
    filter(as.character(weightjaw2) == 0.3)
akrun
  • 874,273
  • 37
  • 540
  • 662