R与Excel中舍入数的差异

时间:2016-12-03 03:22:11

标签: r excel rounding

使用此数据data.frame

数据

dat <- read.table(text = c("
SiteID  cat1    cat2    cat3
Site1   3   1   1
Site1   3   2   2
Site1   2   3   3
Site1   2   1   1
Site1   2   2   2
Site1   1   1   2
Site1   1   3   1
Site1   1   2   3
Site1   3   NA  2
Site1   1   2   NA"),header =T)

我计算了meancat1cat2cat3)和round将其编成R中最接近的整数,如下所示

R结果

library(dplyr)
dat1 <- dat %>% 
  rowwise() %>% 
  mutate(avg = mean(c(cat1, cat2, cat3), na.rm = T),
         avg_round = round(avg))
head(dat1, 10)
# A tibble: 10 × 6
#   SiteID  cat1  cat2  cat3      avg avg_round
#   <fctr> <int> <int> <int>    <dbl>     <dbl>
#1   Site1     3     1     1 1.666667         2
#2   Site1     3     2     2 2.333333         2
#3   Site1     2     3     3 2.666667         3
#4   Site1     2     1     1 1.333333         1
#5   Site1     2     2     2 2.000000         2
#6   Site1     1     1     2 1.333333         1
#7   Site1     1     3     1 1.666667         2
#8   Site1     1     2     3 2.000000         2
#9   Site1     3    NA     2 2.500000         2
#10  Site1     1     2    NA 1.500000         2

2.51.5都已四舍五入为2

这与Excel结果不同,其中2.5已四舍五入为31.5已四舍五入为2。我可以使用ceiling在R中执行相同的操作但天花板会将1.3更改为2,这不是我想要的。

Excel结果

enter image description here

,其中

avg = AVERAGE(B2,C2,D2)
avg_round = ROUND(E2, 0)

为什么1.52.5都已四舍五入到2的任何建议?有没有办法在R中获得相同的Excel结果?

0 个答案:

没有答案