根据其他向量指定的范围对向量中的值求和 [英] Sum the values in a vector according to the range specified by other vectors

查看:43
本文介绍了根据其他向量指定的范围对向量中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 4 个向量:

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)  

我想要做的是,如果向量 v 代表向量 c 并且向量 c 中的数字序列介于 a[i] 和 b[i] 之间,我想对向量 v 中的值求和将向量 v 中的数字相加并将它们存储在一个新向量中.

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.

所以数字 1.5, 1.6, 1.7 在 a[1] 和 b[1] 之间,使得 a[1] <;c[1]、c[2]、c[3]<b[1],因此新向量中的总和为 2+3+3 = 8.我想将此数字存储在一个新向量中,然后移至 a[2] 和 b[2] 并将这些数字与再一次.到目前为止,这是我所拥有的,但是它给了我一个错误:(.

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  
  }

}

推荐答案

你应该看看 ?cut?split,例如:

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

这篇关于根据其他向量指定的范围对向量中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆