Open In App

Weighted Sum in R

Last Updated : 31 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss getting weighted sum in the R programming language.

Weight is basically an integer assigned to each element of data, that signifies the relevance of that element.

Weighted sum = sum of product of two data

Here,

data is a vector/list/dataframe

Example:

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

This operation is performed element-wise multiplication and finally computed the sum of data. We can also first multiply the data and then sum using sum() function

Syntax:

sum(vector*weight)

Example: R program to find the weighted sum of vectors

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))


Output:

[1] 207

Example: R program to create a dataframe with data and weights and get the weighted sum

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))


Output:

[1] 207

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads