[英]Rounding numbers to the nearest values (with different intervals) in R
I want to round (or replace) numbers in a
我想四舍五入(或替换)
a
a <- c(0.505, 1.555, 2.667, 53.850, 411.793)
to the nearest values in b
:到
b
中最接近的值:
b <- c(0, 5, 10, 50, 100, 200, 500)
The output will be this: output 将是这样的:
a_rnd <- c(0, 0, 5, 50, 500)
The logic is simple but I couldn't find any solution, because all the approaches I found require values in b
have an equal interval!逻辑很简单,但我找不到任何解决方案,因为我发现的所有方法都要求
b
中的值具有相等的间隔!
How can I achieve this?我怎样才能做到这一点?
You can use sapply
to loop over all values of a
and use these indexes to extract the proper b
values您可以使用
sapply
循环a
的所有值并使用这些索引来提取正确的b
值
b[sapply(a, function(x) which.min(abs(x - b)))]
#> [1] 0 0 5 50 500
This is a relatively simple approach:这是一个相对简单的方法:
b[apply(abs(outer(a, b, "-")), 1, which.min)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.