One approach is the following:
numVars <- sapply(iris, is.numeric)
iris[numVars] <- lapply(iris[numVars], round, digits = 2)
head(iris)
You can also put it in one lapply() call if you like.
I hope it helps.
Best,
Dimitris
On 8/10/2011 11:34 AM, Liviu Andronic wrote:
Dear all
It is difficult to use round(..., digits=2) on a data frame since one
has to first take care to remove non-numeric variables such as
'character' or 'factor':
head(round(iris, 2))
Error in Math.data.frame(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, :
non-numeric variable in data frame: Species
head(round(iris[1:4], 2))
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 5.1 3.5 1.4 0.2
2 4.9 3.0 1.4 0.2
3 4.7 3.2 1.3 0.2
4 4.6 3.1 1.5 0.2
5 5.0 3.6 1.4 0.2
6 5.4 3.9 1.7 0.4
Is there an elegant way to use round() on a data frame containing
'character' variables without removing them? Thank you
Liviu
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.