Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change decimal digits for data frame column in R

Tags:

r

Questions about displaying of certain numbers of digits have been posted, however, just for single values or vectors, so I hope someone can help me with this.

I have a data frame with several columns and want to display all values in one column with two decimal digits (this column only). I have tried round() and format() and options(digits) but none worked on a column (numerical). I wonder if there is a method to do this without going the extra way of converting the column to a vector and gluing all together again.

Thanks a lot!

like image 987
Kristina Avatar asked Nov 03 '14 18:11

Kristina


People also ask

How do I change a column in a Dataframe in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.


1 Answers

Here's an example of how to do this with the cars data.frame that comes installed with R.

First I'll add some variability so that we have numbers with decimal places:

data=cars+runif(nrow(cars))

Then to round just a single column (in this case the dist column to 2 decimal places):

data[,'dist']=round(data[,'dist'],2)

If your data contain whole numbers then you can guarantee that all values will have 2 decimal places by using:

cars[,'dist']=format(round(cars[,'dist'],2),nsmall=2)
like image 66
CephBirk Avatar answered Oct 14 '22 17:10

CephBirk