R中的加权总和
在本文中,我们将讨论在 R 编程语言中获取加权和。
权重基本上是分配给每个数据元素的整数,表示该元素的相关性。
Weighted sum = sum of product of two data
这里,
数据是向量/列表/数据框
例子:
Consider a vector with 5 elements – c(1,2,3,4,5)
Consider a weight vector with 5 elements – c(2,3,1,2,2)
weighted sum:
(1*2)+(2*3)+(3*1)+(4*2)+(5*2) = 29
这个操作是按元素进行乘法,最后计算数据的总和。我们也可以先将数据相乘,然后使用 sum()函数求和
句法:
sum(vector*weight)
示例: R 程序求向量的加权和
R
# consider the vector1 with 10 elements
vector1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# consider the weight with 10 elements
weight = c(3, 4, 5, 1, 2, 3, 4, 2, 5, 6)
# get the weighted sum
print(sum(vector1*weight))
R
# consider the dataframe with 2 columns 10 elements
data = data.frame(data1=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
weights=c(3, 4, 5, 1, 2, 3, 4, 2, 5, 6))
# get the weighted sum from the dataframe
print(sum(data$data1*data$weights))
输出:
[1] 207
示例: R 程序创建一个包含数据和权重的数据框并获得加权总和
电阻
# consider the dataframe with 2 columns 10 elements
data = data.frame(data1=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
weights=c(3, 4, 5, 1, 2, 3, 4, 2, 5, 6))
# get the weighted sum from the dataframe
print(sum(data$data1*data$weights))
输出:
[1] 207