使用R中的整数计算到第一位小数

Calculate to the first decimal using integers in R

我想使用整数计算到第一位小数,但无论我做什么,它都是四舍五入的,没有给我想要的精度。我花了很多时间查找,似乎很多像我这样的初学者都会遇到问题,但我找不到可以轻松完成的解决方案。

这是我的代码:

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

我明白了:

A   B   C   D 
20  53 200  44

我想要这个:

   A     B      C     D 
20.0  53.3  200.0  44.4

在此先感谢您的帮助。

将要显示的位数增加到 3 个以上到任意数字,然后您会看到 round 的影响。这里 digits 表示要显示的有效位数。

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 

您的四舍五入结果似乎最多有 4 位有效数字。这是您可以使用 options 命令指定的内容。这允许您更改 R 计算结果的方式。

在您的情况下 运行 options(digits = 4) 在您的舍入步骤之前可能会解决问题。