Pork Chop
Pork Chop

Reputation: 29387

Sum the values in a vector according to the range specified by other vectors

I have 4 vectors:

a <- c(1.12,2.30,3.03,4.05)
b <- c(2.03,3.05,4.02,5.03)
c <- c(1.5, 1.6, 1.7, 2.1, 3.3, 3.7,4.1)
v <- c(2,3,3,2,17,13,50)  

What I want to do is I want to sum the values in the vector v if that are representatives of the vector c and if the series of numbers in the vector c are between a[i] and b[i] I want to add the numbers in vector v together and store them in a new vector.

So the numbers 1.5, 1.6, 1.7 are between a[1] and b[1] such that a[1] < c[1], c[2], c[3] < b[1], hence the sum in a new vector is 2+3+3 = 8. I want to store this number in a new vector and then move on to a[2] and b[2] and compare the numbers with c again. This is what I have so far, however it gives me an error :(.

a <- c(1.12,2.30,3.03,4.05)
b <- c(2.03,3.05,4.02,5.03)
c <- c(1.5, 1.6, 1.7, 2.1, 3.3, 3.7,4.1)
v <- c(2,3,3,2,17,13,50)  


i = 1
j = 1
k = 1
p = 1
S1 = NULL
U1 = NULL

while (i < length(c) & j < length(a))
{
  if (c[i] > a[j] & c[i] <= b[j])

    {
    S1[i] <- (v[i])    
    }
    i = i + 1

  U1[k] <- sum(S1) 

  else
  {
    j = j + 1
    k = k + 1  
  }

}

Upvotes: 1

Views: 1062

Answers (1)

sgibb
sgibb

Reputation: 25726

You should have a look at ?cut and ?split, e.g.:

c <- c(1.5, 1.6, 1.7, 2.1, 3.3, 3.7)
v <- c(2,3,3,2, 17,13)

## create corresponding intervals
splits <- cut(c, breaks=1:4)
## split v into intervals and sum them
lapply(split(v, f=splits), sum)
# $`(1,2]`
# [1] 8
#
# $`(2,3]`
# [1] 2
#
# $`(3,4]`
# [1] 30

Upvotes: 2

Related Questions