I am trying to round these values to one digit ( the output values must be 2.4, 0.0 and so on) but when I use round(dataframe, 1)
I get all "0"s or Inf. What is wrong ?
Asked
Active
Viewed 902 times
-1

Andrea Dalla Rosa
- 99
- 1
- 2
- 8
-
1hello :) this is normal behaviour maybe try with `signif()` instead of `round()`, `> round(0.000000001, 1) [1] 0 > signif(0.000000001, 1) [1] 1e-09` – Paul May 05 '20 at 08:07
-
1Ciao Andrea and welcome to SO. First of all you should read [here](https://stackoverflow.com/help/how-to-ask) about how to ask a good question; a good question has better changes to be solved and you to receive help. On the other hand a read of [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) is also good. It explains how to create a reproducible example in R. Help users to help you by providing a piece of your data a desired output and things you have tried so far. Last but not least, are you sure that `round(dataframe, 1)` works? – SabDeM May 05 '20 at 08:16
-
@SabDeM it seems that `round()` can take a dataframe; `round(as.data.frame(iris[1:4]))` produces the expected outcome. – Paul May 05 '20 at 08:26
-
options(scipen = 999) prevents scientific notation – Dr. Flow May 05 '20 at 08:28
1 Answers
0
You can use apply
and round
thus:
Some illustrative data:
set.seed(12)
df <- data.frame(
v1 = rnorm(10),
v2 = rnorm(10),
v3 = rnorm(10)
)
df
v1 v2 v3
1 -1.4805676 -0.77771958 0.2236414
2 1.5771695 -1.29388230 2.0072015
3 -0.9567445 -0.77956651 1.0119791
4 -0.9200052 0.01195176 -0.3024592
5 -1.9976421 -0.15241624 -1.0252448
6 -0.2722960 -0.70346425 -0.2673848
7 -0.3153487 1.18887916 -0.1991057
8 -0.6282552 0.34051227 0.1311226
9 -0.1064639 0.50696817 0.1457999
10 0.4280148 -0.29330515 0.3620647
Solution:
df <- apply(df, 2, round, 1)
df
v1 v2 v3
[1,] -1.5 -0.8 0.2
[2,] 1.6 -1.3 2.0
[3,] -1.0 -0.8 1.0
[4,] -0.9 0.0 -0.3
[5,] -2.0 -0.2 -1.0
[6,] -0.3 -0.7 -0.3
[7,] -0.3 1.2 -0.2
[8,] -0.6 0.3 0.1
[9,] -0.1 0.5 0.1
[10,] 0.4 -0.3 0.4
EDIT:
Alternatively, you can use dplyr
:
library(dplyr)
df %>% mutate_all(round, 1)
And by the way, round(df, 1)
works too!

Chris Ruehlemann
- 20,321
- 4
- 12
- 34
-
May I suggest an improvement, according to the sceenshot attached to the question, numbers are very small, when you `round()` them, you get 0 (ex : round 2,2333e-10 one decimal is 0.0). I think that @Andrea Dalla Rosa was looking for significant digits i.e 2.2333e-10 ----> 2.2e-10. Then function `signif()` is more relevant I think than `round()` – Paul May 05 '20 at 10:54