簡體   English   中英

用於在向量中查找區間總和的 R 函數神秘地返回數字(0),但手動工作正常

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

我制作了以下函數來查找排序數字向量中所有間隔的總和:

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)
    }

嘗試使用它時,我期望一個標量值,但得到numeric(0)

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

但是,當手動執行迭代時,這個想法工作正常:

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

函數有什么問題?

1:length(x) - 1應該是1:(length(x) - 1) 您正在從向量中的每個元素中減去 1。

你真的需要一個循環嗎? 做就是了:

 sum(diff(sort(x)))

我們也可以在沒有循環的情況下做到這一點

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM