简体   繁体   English

用于在向量中查找区间总和的 R 函数神秘地返回数字(0),但手动工作正常

[英]R function for finding sum of intervals in a vector mysteriously returns numeric(0), but works fine manually

I made the following function for finding the sum of all the intervals in a sorted numeric vector:我制作了以下函数来查找排序数字向量中所有间隔的总和:

sum.intervals <- function(x){
        x <- sort(x)
        acc <- 0
        for( i in 1:length(x) - 1 ){
            acc <- acc + x[i + 1] - x[i]
        }
        return(acc)
    }

When trying to use it, I expect a scalar value, but instead get numeric(0) :尝试使用它时,我期望一个标量值,但得到numeric(0)

x <- c(5, 2, 7, 3)
y <- sum.intervals(x)
y
#numeric(0)

However, when performing the iterations manually the idea works fine:但是,当手动执行迭代时,这个想法工作正常:

x <- sort(x)
acc <- 0

i <- 1
acc <- acc + x[i + 1] - x[i]

i <- 2
acc <- acc + x[i + 1] - x[i]

i <- 3
acc <- acc + x[i + 1] - x[i]

acc
#5

What is wrong with the function?函数有什么问题?

1:length(x) - 1 should be 1:(length(x) - 1) . 1:length(x) - 1应该是1:(length(x) - 1) You are subtracting 1 from every element in the vector.您正在从向量中的每个元素中减去 1。

Do you really need a loop here?你真的需要一个循环吗? Just do:做就是了:

 sum(diff(sort(x)))

We can do this without a loop as well我们也可以在没有循环的情况下做到这一点

sum( x[-1] - x[-length(x)])
#[1] 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM