R programming error: sum of products

0 votes

I'm trying to find the sum of products of two different data frames.

data<-a1 a2 a3 a4
      4   6  8  5

Here, a1 a2 a3 a4 are column names

The other data frame is:

data2<-p1 p2 p3 p4
        3  4  5  6
        5  6  8  4
        4  6  6  8
        3  5  8  9

my result should be like this:

result <- a1*P1+a2*p2+a3*p3*a4*p4    

result1 <- 4*3+6*4+8*5+5*6   

result2 <- 4*5+6*6+8*8+5*4   

and so on...

How can this be done?

Mar 6 in Data Analytics by Tyrion anex
• 8,280 points
15 views

1 answer to this question.

0 votes

Best soln is to integrate R linear algebra:

> as.matrix(data2) %*% unlist(data)
#     [,1] 
#[1,]  106
#[2,]  140 
#[3,]  140
#[4,]  151

or you can sweep:

> rowSums(sweep(as.matrix(data2), 2, unlist(data), `*`))
#[1] 106 140 140 151

Where data is:

data=data.frame(a=4,b=6,c=8,d=5)
data2=data.frame(a=c(3,5,4,3),b=c(4,6,6,5),c=c(5,8,6,8),d=c(6,4,8,9))
answered Mar 6 by Sophie may
• 9,430 points

Related Questions In Data Analytics

0 votes
1 answer

“subscript out of bounds” Error in r programming

This error is likely to occur when ...READ MORE

answered Oct 31, 2018 in Data Analytics by Kalgi
• 37,320 points
940 views
0 votes
1 answer

Error: could not find function - R Programming

This error usually occurs when a package ...READ MORE

answered Oct 29, 2018 in Data Analytics by Maverick
• 10,040 points
294 views
0 votes
1 answer

"no applicable method" Error in r programming

This is caused by using an object-oriented ...READ MORE

answered Oct 31, 2018 in Data Analytics by Kalgi
• 37,320 points
46 views
0 votes
1 answer

"subscript out of bounds" error in while executing simple R program

This is caused by trying to access ...READ MORE

answered Oct 31, 2018 in Data Analytics by Kalgi
• 37,320 points
67 views
0 votes
1 answer

R programming error

Alright, you can either use gsub to match the ...READ MORE

answered Dec 18, 2018 in Data Analytics by Tyrion anex
• 8,280 points
16 views
0 votes
1 answer

R Programming: Market Basket Analysis Error

The basket.sorted() has less than 5 rules. Refer ...READ MORE

answered Feb 11 in Data Analytics by Sophie may
• 9,430 points
88 views
0 votes
1 answer

R Programming: regexpr error

The below code will help: gregexpr("D", x) # [[1]] # ...READ MORE

answered Feb 21 in Data Analytics by Tyrion anex
• 8,280 points
21 views
0 votes
1 answer

R programming: Graphs

Try this: ggplot(dfc, aes(x=x, y=y, colour=f, fill=f, ymin=y-se, ...READ MORE

answered Feb 21 in Data Analytics by Tyrion anex
• 8,280 points
18 views
0 votes
1 answer

R programming: Unexpected symbol error

Format your code this way: myfunction <- function() ...READ MORE

answered Dec 17, 2018 in Data Analytics by Sophie may
• 9,430 points
162 views
0 votes
1 answer

R Programming error in 'fert'

You're using a factor: fert <- factor(c(50,20,10,10,20,50)) levels(fert) #[1] ...READ MORE

answered Dec 27, 2018 in Data Analytics by Sophie may
• 9,430 points
37 views