Using this dat data.frame
DATA
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)
I calculated the mean (of cat1 , cat2 and cat3) and rounded it to the nearest integer in R as below
R results
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
Both 2.5 and 1.5 have been rounded to 2
This is different from Excel results where 2.5 has been rounded to 3 and 1.5 has been rounded to 2. I can do the same in R using ceiling but ceiling will change 1.3 to 2 which is not what I want.
Excel results
where
avg = AVERAGE(B2,C2,D2)
avg_round = ROUND(E2, 0)
Any suggestions why 1.5 and 2.5 both have been rounded to 2? and is there any way to get the same Excel results in R?
