如何解决是否有一个函数将 x 映射到给定值的最接近倍数,其编码比我的“分类”更清晰?
我的函数是建立在非常基本的元素之上的,不知道有没有更通用更直接的解决方案。
# function mapping x to the nearest multiple of a given value
# with lower_limit included (or excluded if right = TRUE)
classify <- function(x,class_width,right = FALSE)
if (right)
ceiling(ceiling(x-class_width/2)/class_width)*class_width else
floor(floor( x+class_width/2)/class_width)*class_width
cw <- 3
z <- c(c(-.5,.5)+cw/2)
z <- c(z,z + cw)
z <- sort(c(-z,z))
cbind(z,cls_left = classify(z,cw),cls_right = classify(z,cw,T))
#> z cls_left cls_right
#> [1,] -5.0 -6 -6
#> [2,] -4.5 -3 -6
#> [3,] -4.0 -3 -3
#> [4,] -2.0 -3 -3
#> [5,] -1.5 0 -3
#> [6,] -1.0 0 0
#> [7,] 1.0 0 0
#> [8,] 1.5 3 0
#> [9,] 2.0 3 3
#> [10,] 4.0 3 3
#> [11,] 4.5 6 3
#> [12,] 5.0 6 6
由 reprex package (v2.0.0) 于 2021 年 6 月 6 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。