Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R round to nearest .5 or .1

Tags:

rounding

r

r-faq

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 for each stock. Here are some examples:

Current Stock Price         Minimum Tick Increment       Desired Output   123.45                            .50                      123.50   155.03                            .10                      155.00   138.24                            .50                      138.00   129.94                            .10                      129.90    ...                              ...                       ... 

I'm not really sure how to do this but am open to suggestions.

like image 914
screechOwl Avatar asked Dec 29 '11 07:12

screechOwl


People also ask

How do I round to .5 in R?

round rounds the values in its first argument to the specified number of decimal places (default 0). Note that for rounding off a 5, the IEEE standard is used, ``go to the even digit''. Therefore round(0.5) is 0 and round(-1.5) is -2 .

What is 0.5 rounded?

0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number. Hence, the whole number of 0.5 will be 1.


2 Answers

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 
like image 24
ledmirage Avatar answered Sep 23 '22 17:09

ledmirage


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 
like image 65
kohske Avatar answered Sep 23 '22 17:09

kohske