koteletje
koteletje

Reputation: 679

for loop results in unexpected result

I want to know all the possible (positive) differences between all elements of an ordered vector (containing only positive elements).

To do so, I created another vector that I let grow using a for loop (see Code 1). It did not lead to the desired result "1 4 6 3 5 2" but to "12". When I apply Code 2 (which seems equivalent to Code 1...), I get the desired result though... Does anyone know why the two codes below do not lead to the same result?

Code 1

a = c()
b = c(1,2,5,7)

for (i in (length(b)-1)) {

   a = unique(c(a,b[(i+1):length(b)] - b[i]))

}

Code 2

a = c()
b = c(1,2,5,7)
i=1
a = unique(c(a,b[(i+1):length(b)] - b[i]))
i=2
a = unique(c(a,b[(i+1):length(b)] - b[i]))
i=3
a = unique(c(a,b[(i+1):length(b)] - b[i]))

I am a bit puzzled...

Upvotes: 0

Views: 72

Answers (2)

Benjamin
Benjamin

Reputation: 11850

This can be accomplished more succinctly with:

as.vector(dist(a))

Upvotes: 2

Zheyuan Li
Zheyuan Li

Reputation: 73265

You will hate yourself once you know it. You need

for (i in 1:(length(b)-1))

rather than

for (i in (length(b)-1))

Upvotes: 1

Related Questions