1

I would like to calculate to the first decimal using integer numbers but whatever I do, it is rounded and does not give me the precision I want. I have spent a lot of time looking up and it seems something a lot of beginners like me would have a problem with but I cannot find a solution to what could be done easily.

Here are my codes:

type = c('A', 'B', 'C', 'D', 'C', 'B')
count = c(1, 4, 8, 4, 2, 4)
df1 = data.frame(type, count)

type2 = c('A', 'B', 'C', 'D', 'B', 'C', 'D', 'A')
count2 = c(3, 7, 1, 4, 8, 4, 5, 2)
df2 = data.frame(type2, count2)

sum1 <- tapply(df1$count, type, sum)
sum2 <- tapply(df2$count2, type2, sum)

round(sum1/sum2*100.0, 1) # Want to calculate it to the 1st decimal

I get this:

A   B   C   D 
20  53 200  44

and I want this:

   A     B      C     D 
20.0  53.3  200.0  44.4

I appreciate your help in advance.

owl
  • 1,841
  • 6
  • 20
  • 30
  • 2
    Run `options(digits = 4)` in the console and try again. – Ronak Shah Jun 20 '20 at 02:02
  • Thank you again, that did the trick! I have tried using options() but I had somehow assumed that digits designate the decimals and was doing options(digits = 1), which of course did not solve the problem. – owl Jun 20 '20 at 02:10

2 Answers2

2

It seems like your rounded result is supposed to have a maximum of 4 significant digits. This is something you can specify using an options command. This allows you to change the way R computes results.

In your case running options(digits = 4) before your rounding step probably solves the issue.

questionmark
  • 335
  • 1
  • 13
1

Increase the number of digits to be displayed more than 3 to any number and then you'll see impact of round. Here digits represent number of significant digits to be displayed.

options(digits = 10)
round(sum1/sum2*100, 1)

#    A     B     C     D 
# 20.0  53.3 200.0  44.4 


round(sum1/sum2*100, 2)

#    A      B      C      D 
# 20.00  53.33 200.00  44.44 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks! As you said, I added options(digits = 4) and that did the trick. In my case, digits = 4 was sufficient as you initially told me. – owl Jun 20 '20 at 06:51