Amy
Amy

Reputation: 7

adding first k components of a vector in R

I have a vector called test = c(1,3,2,10,11,9). I need to calculate the sum of components such that 1,1+3,1+3+2, .....,1+3+2+10+11+19 and then store all these values in a vector. And then I need to find the maximum in the vector and see which position is the maximum in. My code is below but it won't get me the right sum in the vector.

for(k in 1:length(test){
  val = numeric(length(test)) #create an empty vector of length 6 to store the sums
  val= c(1:length(test))*0    #fill the vector with 0
  val[k] = sum(test[1:k]) #sum from 1 to k and store in the vector
}
print(val)

max(val) #find the maximum from the vector of sums
which.max(val) #find the index of the maximum

Upvotes: 0

Views: 42

Answers (1)

Alex Reynolds
Alex Reynolds

Reputation: 96967

You are clobbering val on every step through your for loop. Move your initialization steps out of the loop.

Upvotes: 1

Related Questions