R round to nearest .5 or .1

后端 未结 4 437
忘了有多久
忘了有多久 2020-11-27 15:44

I have a data set of stock prices that have already been rounded to 2 decimal places (1234.56). I am now trying to round to a specific value which is different

相关标签:
4条回答
  • 2020-11-27 16:06

    I'm not familiar with R the language, but my method should work with any language with a ceiling function. I assume it's rounded UP to nearest 0.5:

    a = ceiling(a*2) / 2
    
    if a = 0.4, a = ceiling(0.4*2)/2 = ceiling(0.8)/2 = 1/2 = 0.5
    if a = 0.9, a = ceiling(0.9*2)/2 = ceiling(1.8)/2 = 2/2 = 1
    
    0 讨论(0)
  • 2020-11-27 16:09

    The taRifx package has just such a function:

    > library(taRifx)
    > roundnear( seq(.1,1,.13), c(.1,.1,.1,.2,.3,.3,.7) )
    [1] 0.1 0.2 0.3 0.4 0.6 0.6 0.7
    

    In your case, just feed it the stock price and the minimum tick increment as its first and second arguments, and it should work its magic.

    N.B. This has now been deprecated. See comment.

    0 讨论(0)
  • 2020-11-27 16:12

    Like what JoshO'Brien said in the comments: round_any in the package plyr works very well!

    > library(plyr)
    > stocks <- c(123.45, 155.03, 138.24, 129.94)
    > round_any(stocks,0.1)
    [1] 123.4 155.0 138.2 129.9
    > 
    > round_any(stocks,0.5)
    [1] 123.5 155.0 138.0 130.0
    > 
    > round_any(stocks,0.1,f = ceiling)
    [1] 123.5 155.1 138.3 130.0
    > 
    > round_any(stocks,0.5,f = floor)
    [1] 123.0 155.0 138.0 129.5
    

    Read more here: https://www.rdocumentation.org/packages/plyr/versions/1.8.4/topics/round_any

    0 讨论(0)
  • 2020-11-27 16:16

    Probably,

    round(a/b)*b
    

    will do the work.

    > a <- seq(.1,1,.13)
    > b <- c(.1,.1,.1,.2,.3,.3,.7)
    > data.frame(a, b, out = round(a/b)*b)
         a   b out
    1 0.10 0.1 0.1
    2 0.23 0.1 0.2
    3 0.36 0.1 0.4
    4 0.49 0.2 0.4
    5 0.62 0.3 0.6
    6 0.75 0.3 0.6
    7 0.88 0.7 0.7
    
    0 讨论(0)
提交回复
热议问题