5

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!

2
  • 1
    Can you show what you have tried (code)? Commented Nov 3, 2014 at 19:02
  • Unfortunately not, deleted it all when it didn't work.. :( Commented Nov 3, 2014 at 20:37

1 Answer 1

11

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that CephBirk, I can see the logic behind it, unfortunately it didn't work. The problem is that I am actually dividing 4 digit numbers (e.g. 8000) by 100 to get 80.00 (this is a decimal time measure), so somehow R doesn't want to display it. Tried changing the numbers with Excel, but doesn't feed into R, when adding an actual number with two decimal places (e.g. 0.01) to the top of the column, R displays the rest as 80.00 but as soon as I delete the 0.01 R jumps back to 80. Happen to know of a way just to put a dot behind the second digit?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.