0

I would like to filter a dataframe based on last two decimal on particular column. So, the data is something like this:

     [91] 22.6300 22.6300 22.6700 22.6200 22.6700 22.6200 22.6400 22.6600 22.6600
    [100] 22.6600 22.6800 22.6800 22.6800 22.6800 22.6600 22.6700 22.7000 22.7000
    [109] 22.7000 22.7200 22.6800 22.7000 22.6800 22.6900 22.7000 22.6975 22.7000
    [118] 22.6900 22.6900 22.7000 22.6800 22.7200 22.7200 22.7200 22.7200 22.7400
    [127] 22.7500 22.7500 22.7500 22.7500 22.7200 22.7528 22.7210 22.7500 22.7500
    [136] 22.7210 22.7210 22.7402 22.7200 22.7300 22.7700 22.7500 22.8100 22.8100
    [145] 22.8100 22.8100 22.8100 22.8100 22.8000 22.8000 22.8000 22.8000 22.7850
    [154] 22.8000 22.7900 22.8000 22.8000 22.8000 22.8000 22.8000 22.8000 22.8011

Let's say the column name is PRICE in my_data dataframe. How can I filter based on the last decimal of the PRICE column?. The end goal is I want to get a dataframe with decimal ends with 0.0001 to 0.0010. For instance:

   22.6975 22.7528 22.7210 22.7402 22.8011

Should be included to my filtered dataframe, because they end with 5, 8, 10, 2, and 1 respectively.

Thank you!

stalefriedrice
  • 29
  • 1
  • 2
  • 8
  • 1
    Help people help you by making your question reproducible as outlined [in this question](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Chase Feb 24 '19 at 03:19
  • 1
    How do those 5 number fit the rule you expressed. Looks to me that they should mostly fail. – IRTFM Feb 24 '19 at 07:57

2 Answers2

2

I would extract the decimal portion of your values and create a boolean off of that. Here's one solution:

#make random numbers that roughly match OPs
set.seed(42)
x <- 22 + runif(1000)
decs <- (x - floor(x))
x[decs > 0.0001 & decs < 0.0010]
#> [1] 22.00024 22.00041

Created on 2019-02-23 by the reprex package (v0.2.1)

Chase
  • 67,710
  • 18
  • 144
  • 161
0

You can also try this:

deciRule <- 0.4

x[(x %% 1) < deciRule]

[1] 22.02223 22.23572

Sample data:

set.seed(42)
x <- 22 + runif(10)
[1] 22.81985 22.53936 22.49902 22.02223 22.55409
[6] 22.71990 22.23572 22.81188 22.42147 22.56491
DJV
  • 4,743
  • 3
  • 19
  • 34