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)
:
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)
. You are subtracting 1 from every element in the vector.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.