Thursday, September 21, 2017

round() signif() {base}


round() function rounds the values in its first argument to the specified number of decimal places (default 0).

signif() function rounds the values in its first argument to the specified number of significant digits.

round(x, digits = 0) 
signif(x, digits = 6)

The parameters are:
 -x: numeric vector
 -digits: integer to indicate the number of decimal places or significant digits.

Round():
x = c(1.2346578, 1.24367, 1.78511, 1.536)
round(x,2)
## [1] 1.23 1.24 1.79 1.54
The numbers are rounded to have two decimal places. In the third and fouth place we see that is has been rounded up due to the following decimals in the original numbers.
round(x,3)
## [1] 1.235 1.244 1.785 1.536
In this case, the first and second numbers have been rounded up.
y = c(1.2346578, 11.24367, 111.78511, 1111.536)
round(y,-1) #rounds the numbers previous to the decimal places
## [1]    0   10  110 1110
round(y,-2)
## [1]    0    0  100 1100
z = c(123.23, 245.24, 667.78, 664.53)
round(z,-1) #rounds the numbers previous to the decimal places.
## [1] 120 250 670 660
round(z,-2)
## [1] 100 200 700 700
We can see that some numbers have been rounded up, while others have been rounded down.

Signif():
While round() rounds the values to a specific number of decimal places signif() rounds the value to sigfinicant digits (all the places of the number, not just decimal places).
r = c(1.2346578, 11.24367, 111.78789, 1111.16789)
r
## [1]    1.234658   11.243670  111.787890 1111.167890
round(r,2)
## [1]    1.23   11.24  111.79 1111.17
signif(r,2)
## [1]    1.2   11.0  110.0 1100.0
round(r,5)
## [1]    1.23466   11.24367  111.78789 1111.16789
signif(r,5)
## [1]    1.2347   11.2440  111.7900 1111.2000

Plot round() and signif() using the variable Sepal.Length from the iris dataset:
NoFunction = summary(iris$Sepal.Length)
Round = round(summary(iris$Sepal.Length), 1)
Signif = signif(summary(iris$Sepal.Length), 1)
NoFunction
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   4.300   5.100   5.800   5.843   6.400   7.900
Round
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     4.3     5.1     5.8     5.8     6.4     7.9
Signif
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##       4       5       6       6       6       8
boxplot(NoFunction,Round,Signif, col = c('darksalmon', 'salmon', 'darkred'), names = c('NoFunction', 'Round', 'Signif'), ylab= 'iris$Sepal.Length')

No comments:

Post a Comment

duplicated() {base}

duplicated()  function determines which elements are duplicated and returns a logical vector. The parameters of the function are:   ...