[R] round() a data frame containing 'character' variables?

Liviu Andronic landronimirc at gmail.com
Thu Aug 11 20:47:14 CEST 2011


On Wed, Aug 10, 2011 at 5:52 PM, Jean V Adams <jvadams at usgs.gov> wrote:
> data.frame(lapply(x, function(y) if(is.numeric(y)) round(y, 2) else y))
>
Building on this, I came up with a 'data.frame' method for round().
I'm not sure how orthodox it is, but it seems to do the job as
intended:
round.data.frame <-
    function(x, digits = 0)
{
    data.frame(lapply(x, function(y) if(is.numeric(y)) round(y, digits) else y))
}

Here's an example:
> set.seed(2)
> x <- data.frame(a=rnorm(10), b=rnorm(10), c=rnorm(10), d=letters[1:10])
> print(x, digits=2)  ##it displays 2, 3 or 4 digits, instead of the desired 2
       a      b       c d
1  -0.90  0.418  2.0908 a
2   0.18  0.982 -1.1999 b
3   1.59 -0.393  1.5896 c
4  -1.13 -1.040  1.9547 d
5  -0.08  1.782  0.0049 e
6   0.13 -2.311 -2.4517 f
7   0.71  0.879  0.4772 g
8  -0.24  0.036 -0.5966 h
9   1.98  1.013  0.7922 i
10 -0.14  0.432  0.2896 j
> round(x, 2)
       a     b     c d
1  -0.90  0.42  2.09 a
2   0.18  0.98 -1.20 b
3   1.59 -0.39  1.59 c
4  -1.13 -1.04  1.95 d
5  -0.08  1.78  0.00 e
6   0.13 -2.31 -2.45 f
7   0.71  0.88  0.48 g
8  -0.24  0.04 -0.60 h
9   1.98  1.01  0.79 i
10 -0.14  0.43  0.29 j

Would such a method get any chance of inclusion in 'base'? Regards
Liviu



More information about the R-help mailing list