Samyak Gupta
Samyak Gupta

Reputation: 29

How to round off the output from the predict function in r

a = today+1; b = today+7
new <- data.frame(t_date = as.Date(a:b ,origin = "2020-01-20"))
predict_date <- as.Date(a:b,origin="2020-01-20")
predict_date = c(as.character.Date(predict_date))  
Final <- cbind(predict_date,predict.lm(fit,new,interval = "confidence"))
knitr::kable(Final,caption = "This is the predictions for the world ")

The Output I got was this

I want the output as an integer, Someone please help me with this issue!

Upvotes: 1

Views: 2289

Answers (2)

deeksha daga
deeksha daga

Reputation: 15

this should work in you case ->

Final$fit <- round(Final$fit)
Final$lwr <- round(Final$lwr)
Final$upr <- round(Final$upr)

Upvotes: 0

Richie Cotton
Richie Cotton

Reputation: 121077

To control the number of digits in the printing of the output, set the digits argument to kable().

To control the precision of the actual numbers, user round().

Here is a reproducible example.

library(dplyr)
library(knitr)

mdl <- lm(dist ~ speed, data = cars)

explanatory_data <- data.frame(
  speed = seq(0, 100, 10)
)

predictions <- explanatory_data %>% 
  mutate(
    dist = predict(mdl, explanatory_data)
  )

By default, kable() prints as many digits as getOption("digits").

predictions %>% 
  kable()

| speed|      dist|
|-----:|---------:|
|     0| -17.57909|
|    10|  21.74499|
|    20|  61.06908|
|    30| 100.39317|
|    40| 139.71726|
|    50| 179.04134|
|    60| 218.36543|
|    70| 257.68952|
|    80| 297.01361|
|    90| 336.33769|
|   100| 375.66178|

Change this with the digits argument.

predictions %>% 
  kable(digits = 2)

| speed|   dist|
|-----:|------:|
|     0| -17.58|
|    10|  21.74|
|    20|  61.07|
|    30| 100.39|
|    40| 139.72|
|    50| 179.04|
|    60| 218.37|
|    70| 257.69|
|    80| 297.01|
|    90| 336.34|
|   100| 375.66|

That doesn't change the underlying number. You can change the precision using round() (but that's usually a bad idea, since any further calculations will be less accurate).

predictions %>% 
  mutate(rounded_dist = round(dist, 2))

   speed      dist rounded_dist
1      0 -17.57909       -17.58
2     10  21.74499        21.74
3     20  61.06908        61.07
4     30 100.39317       100.39
5     40 139.71726       139.72
6     50 179.04134       179.04
7     60 218.36543       218.37
8     70 257.68952       257.69
9     80 297.01361       297.01
10    90 336.33769       336.34
11   100 375.66178       375.66

Upvotes: 1

Related Questions