此问题以前已经被提出:如何在R中对数据框的数字进行四舍五入并保留总和?
我还想在dplyr中实现这个功能,根据所需的数字位数进行四舍五入并保持整体一致性:
round_preserve_sum <- function(x, digits = 0) {
up <- 10 ^ digits
x <- x * up
y <- floor(x)
indices <- tail(order(x-y), round(sum(x)) - sum(y))
y[indices] <- y[indices] + 1
y / up
}
以下是一个数据框:
df <- data.frame(SAND = c(0.00000, 28.00000, 27.27273),
SILT = c(45.45455, 35.00000, 34.34343),
CLAY = c(54.54545, 37.00000, 38.38384))
使用这个函数和这些值分别,我得到了:
round_preserve_sum(c(0.00000, 45.45455, 54.54545), 0)
[1] 0 45 55
round_preserve_sum(c(28.00000, 35.00000, 37.00000), 0)
[1] 28 35 37
round_preserve_sum(c(27.27273, 34.34343, 38.38384), 0)
【1】27、34、39
这三个数的总和为100。
当我在dplyr中实现这个函数时:
df.Rd0 <-df %>%
mutate(across(c(SAND, SILT, CLAY), ~round_preserve_sum(.,0)),
Sum = SAND + SILT + CLAY)
我会:
SAND SILT CLAY Sum
1 0 46 55 101
2 28 35 37 100
3 27 34 38 99
不使用波浪符号:
df.Rd0 <-df %>%
mutate(across(c(SAND, SILT, CLAY), round_preserve_sum(.,0)),
Sum = SAND + SILT + CLAY)
我收到了这个错误信息:
Error : Problem with `mutate()` input `..1`.
i `..1 = across(c(SAND, SILT, CLAY), round_preserve_sum(., 0))`.
x undefined columns selected
我猜这个函数没有为向量编程?
Error in aplyfun(.Call(Cpp_mrtl, do.call(cbind, X), FALSE, 0L), FUN, ...) : la fonction 'Rcpp_precious_remove' n'existe pas dans le package 'Rcpp'
。我加载了Rcpp并再次尝试,但出现了错误。 - Marc-Olivier Gasserpmap
吗? - akrunpmap
,您可以使用以下代码:df %>% select(yourcols) %>% pmap_dfr(~ {tmp <- round_preserve_sum(c(...), 0) c(tmp, Sum = sum(tmp))})
。如果有更多的列,则可以将其与其他列绑定。 - akrun